Search code examples
google-chrome-extension

Chrome extension with manifest v3 inject external code


The code I need my extension to inject changes often so it's inpractical to bundle script with extension because it's to much burden for end user to constantly update their extension several times a day. This extension is not public and for company use only so it doesn't have to be in Chrome store.

I am getting CSP error when doing this:

chrome.scripting.executeScript({
    target: { tabId: details.tabId },
    files: [ 'https://www.example.com/script.js' ]
})

Tried this:

"content_security_policy": {
   "script-src": [ "self", "https://*.example.com/*" ],
   "object-src": [ "self", "https://*.example.com/*" ]
},

Doesn't work.


Solution

  • Found out how to do it:

    const dynamicScript = fetch(...);
    const data = {}   // to pass into dynamic script
    
    chrome.scripting.executeScript(
       {
          target: { tabId: details.tabId },
          world: "MAIN",     // most important part
          func: data => {
             (new Function('data', dynamicScript))(data);
          },
          args: [data]  // passing app into func above
       }
    ); 
    

    world: "MAIN" bypasses CSP imposed by Chrome extension host. If page has CSP defined (most don't) then you'll also have to modify headers to exclude those. Not shown here.