My R Shiny app contains two different JS scripts in the UI:
- One to load the msal library
shiny::tags$script(src="https://alcdn.msauth.net/browser/2.30.0/js/msal-browser.min.js")
- And another custom script that uses that library to runs some db oauth token negotiation:
shiny::tags$script(HTML("
async function wrapperFunc() {
const msalConfig = {
auth: {
clientId: 'XXXX',
authority: 'XXXXX'
}
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
const silentRequest = {
scopes: ['api://XXXXX']
};
const callLogin = async function(silentRequest, msalInstance) {
try {
const loginResponse = await msalInstance.loginPopup(silentRequest);
return loginResponse;
} catch (err) {
console.log(err)
}
}
response = callLogin(silentRequest, msalInstance);
return response;
}
wrapperFunc().then(result => {
Shiny.setInputValue('oauthToken', result['accessToken']);
console.log(result['accessToken']);
});"))
Is there a way to combine the two tags$script
calls into one? I am asking because I would like to create a catch-all custom function that encapsulates the two, because it is a standard bit of code used in all reporting across my organization. Packaging this bit of code would remove the need to copy and paste the JS scripts across different reports.
I hope I am making sense!
Thanks
2
Answers
It was super simple - wrap them both up in a tags$head script!
Yes, you may merge the two
tags$script
calls into a single JavaScript function that loads themsal
library and executes your own code. This method may then be called in a singletags$script
block. Here’s an example of how it may be done:The
initializeMsalAndRunCustomCode
method is defined in this example to dynamically load themsal
library and then run your custom code. In the Shiny UI, this method is called within a singletags$script
block. This method allows you to encapsulate typical JavaScript functionality and just load the library once in your Shiny app.