1

I am trying to load (inject) in page a javascript code. The javascript file is local to the extension. the filepath is 'js/somefile.js'.

const basePath = chrome.runtime.getURL('');
    fetch(chrome.runtime.getURL(filePath), { mode: 'same-origin' }) // <-- important
      .then((_res) => _res.blob())
      .then((_blob) => {
        const reader = new FileReader();
        reader.addEventListener('loadend', (data) => {
          callback(data.currentTarget.result, basePath);
        });
        reader.readAsText(_blob);
      });

const scriptTag = document.createElement('script');
    scriptTag.innerHTML = scriptText;
    scriptTag.type = 'text/javascript';
    const scriptElement = document[injectLocation].appendChild(scriptTag);
    if (removeImmediately) document[injectLocation].removeChild(scriptElement);

My web accessible resources are:

"web_accessible_resources": [{
    "resources": [
    "js/*.js",
    ],
    "matches": ["<all_urls>"]
  }],

"content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self'",
    "sandbox": "sandbox allow-scripts; script-src 'self' 'https://apis.google.com/' 'https://www.gstatic.com/' 'https://*.firebaseio.com' 'https://www.googleapis.com' 'https://ajax.googleapis.com'; object-src 'self'"
  },

The error that I get is:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-Wq/CW2mxkri68TjkuaA0+LnU0capVpyiEuSA5NOVNfU='), or a nonce ('nonce-...') is required to enable inline execution.
Michael
  • 1,229
  • 1
  • 14
  • 21
  • The code you've shown is unrelated to the error which says you have an inline script which is a common problem in the popup or options pages: [more info](https://stackoverflow.com/a/25721457). – wOxxOm May 07 '21 at 17:14
  • You are right, Indeed I am trying to inject said script in page. I saw that executeScript is a viable alternative. How can I aim to inject the code of a script in the current tab? – Michael May 07 '21 at 18:01
  • Use a [content script](https://stackoverflow.com/a/4532567). – wOxxOm May 07 '21 at 18:08
  • I updated the code with the offending line. It is the appendchild part that is blocked because V3 does not allow for injection of scripts. I am using a content script to do this but it still fails. – Michael May 07 '21 at 18:10
  • 1
    Currently you use a content script to inject another script in [page context](/a/9517879), which is a very special thing needed to extract/access JS variables/functions from the page. To inject the code you don't need that. Simply inject the js file as a content script (declaratively or via executeScript). – wOxxOm May 07 '21 at 18:17
  • I see makes a lot more sense now, thank you – Michael May 07 '21 at 18:19

0 Answers0