Getting a plugin Handler class URL from client side (JS)

Updating,

me and my team arrived at a solution for this problem.

Inspired on the lib.pkp.classes.template.PKPTemplateManager.registerJSLibraryData() method, we can get the plugin Handlers URLs and pass it on for the JavaScript code to call it.

The base URI can be obtained with the lib.pkp.classes.handler.PKPHandler.getDispatcher() method.

So using both methods, and inspired by the tinyMCE plugin we could send the URLs to the JavaScript by doing this:

function addHandlersURLsToJavaScript($request, $templateManager){ 

$baseUrl = $request->getDispatcher()->url($request, ROUTE_COMPONENT) . 'plugins/generic/name-application/handlers/name-application/'; 
$nameOfTheFunctionToBeCalledOnHandler = $baseUrl . 'name-of-the-function-to-be-called-on-handler'; 

$data = [ 
'nameOfTheFunctionToBeCalledOnHandler' => $nameofthefunctiontobecalledonhandler 
]; 

$templateManager->addJavaScript('AppData', 'app = ' . json_encode($data) . ';', [ 
'inline' => true, 
]); 
}

On the JavaScript side of the plugin it looks like this:

async function useSomeHandlerFunction(){
    const response = await fetch(app.nameOfTheFunctionToBeCalledOnHandler); 
    const something = await response.json();
    return something;
}
4 Likes