简体   繁体   中英

Loading external javascript in a Chrome Extension

I'm trying to load some external javascript code in my Chrome extension. However, due to the sandboxed environment of the extension, I can't see any of the functions defined by the external code.

The external code implements a dependency mechanism, whereby one javascript file may require another, and so forth. It also looks at arguments to the URL used to load the javascript to determine the top level javascript file to load. So it basically is able to load any arbitrary web app, and it is not known in advance all the files that will be used. So I can't use any static definitions in the extension.

There is also the issue that since all extension code is sandboxed, I don't have complete access to the document - for instance, it can't access the window variable.

But if I put all the code in the external code, I run into content security problems if one script tries to load another. The whole reason I went was an extension is because of the bone-headed misimplementation of CSP by every single browser in existence whereby bookmarklets can't access external resources.

What's the best practice for bypassing or working around the extension sandbox to basically be able to run code as if the page itself had loaded it, without any issues with CSP?

In the content script you could do something like this to load the js file

function inject(url, exteral) {
    // 1. Build the absolute URL
    // 2. Create a script tag and set src attribute
    // 3. Append script tag to thw window
    if (!external){
       url = chrome.extension.getURL(url);
    }
    var scriptElement = document.createElement('script');
    scriptElement.src = url;
    (document.body || document.head || document.documentElement).appendChild(scriptElement);
}

If the js file is packged with the extension, it must be placed in the manifest.json under web_accesible_resources . othwerwise it need to have the same protocol that the page it is injected in (http | https)

Since the content script is not allowed to call the window functions, you could call window.postMessage to send data from the actual window to content script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM