2

I need to use a 3rd patty JS library in my LWC component in a LWR community. Looks like platformResourceLoader is not working in LWR, so it's not possible to load script from static resources as usually, it throws error "lwr_bootstrap_locker:14 Not allowed to load local resource: blob". I tried to load the script manually

const libraryScript = document.createElement('script');
libraryScript.src = scriptURL;
document.getElementsByTagName('head')[0].appendChild(this.libraryScript);

It causes the same error.

I try to load the script directly in a community head

<script src="/sfsites/c/resource/LibraryFolder/library.js"></script>

and then call it from my LWC, like I do with script loaded by platformResourceLoader

window.libraryFunc();

But LWC doesn't see this func in window var(there is no typo, the same function works in Lightning).

Only one way that I found is to add two scripts to the head, the first one loads the library and the second adds listener to the document and calls my function on cathing event

<script src="/sfsites/c/resource/LibraryFolder/library.js"></script>
<script>
document.addEventListener('myevent', (event) =>  libraryFunc(event.detail));
</script>

and then dispatch this event from my LWC

document.dispatchEvent(new CustomEvent("myevent", {detail}));

It works for me, but it looks like a dirty hack, is there a better solution to use the JS library in a LWR site?

1 Answer 1

0

You can implement your own version of platformResourceloader

import jquery from '@salesforce/resourceUrl/jquery';
...
connectedCallback(){
...
this.loadScript(jquery);
//instead of loadScript(this, jquery);
...
}
...

loadScript(url) {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = url;
        script.charset = 'utf-8';
        script.type = 'text/javascript';
        document.head.appendChild(script);
        script.addEventListener('load', resolve);
        script.addEventListener('error', reject);
    })
}

Alternatively you can host the Script outside Salesforce and try accessing it within LWR via privileged scripts.

Make use of the tag

You must log in to answer this question.

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