2

I have created a LWC component that loads a third party library from a static resource.

Here's an example of the library:

window.myLib = (function() {
    return {
        myFunction: function(a, b) {
            return a * b;
        }
    };
}());

Once the library is loaded, I should be able to access the library in the parent web component through the following syntax:

Promise.all([
    loadScript(this, library +   '/script.js'),
]).then(() => {
   //This works when the component is loaded internally (e.g. embedded on a record)
   let result = myLib.myFunction(2,2);
   debug('Results', result);
   //This also works when the component is loaded internally
   let result = window.myLib.myFunction(2,2);
   debug('Results', result);
}).catch(err => {
    debug('Failed to load full calendar', err?.message);
});

However, the issue I am facing is that when the LWC component is embedded in a Build Your Own (LWR) Digital Experience, the script throws an error "myLib is undefined".

Setup:

  • Lightning Web Security is enabled (instead of Lightning Locker)

What is peculiar is that upon logging the "window" object, we can see in the console that the window object contains our library, however attempting to directly access the global function "myFunction" returns as undefined.

//The chrome console reports that there is a property "myLib" on window
console.log(window)
//Output is undefined
console.log(typeof myLib)
//Output is undefined
console.log(window.myLib)
//Error thrown "cannot read property myFunction of undefined 
console.log(window.myLib.myFunction)

What we tried so far:

  • renderMode = 'light'; on the web component

  • converting the library to UMD format

  • converting the library to a module

  • added an exception in the .eslintrc.json file for our library that looks like this:

    { "globals": { "myLib":true } }

  • placed the .eslintrc.json in the lwc folder

  • placed the .eslintrc.json in the root project directory

  • updated the package.json to add global lint exception

    "eslintConfig": { "globals": { "FullCalendar": true } }

  • added /* global myLib */ to the header of the LWC class

Our observation is that this is LWR specific issue as we are using the same library for our internal facing LWC components. Has anyone dealt with a similar issue?

2

1 Answer 1

0

After some research, the platformResourceLoader API seems to be the issue. Here's Salesforce's stance:

Scripts loaded through lightning/platformResourceLoader run in system mode outside of a Lightning Locker sandbox. As a result, the component loading the script doesn’t have access to the same global variable scope as the script itself, preventing it from accessing any global variable set by the script

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .