1

I have a Chrome extension in V2. I am trying to migrate it to Chrome V3. In the code I am trying to append a node using appendChild.

Code snippet I have used to inject the java script to the DOM of page been opened by Browser is as below.

var injectScript = function() {
    var node = document.createElement('script');
    var jscode = '(' + <some code> +  ')();';
    node.innerHTML = jscode;
    document.head.appendChild(node);
};

Changes done in manifest.json for v3

"content_security_policy": {
   extension_pages": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

Chrome extension is showing below error message. Refused to execute inline script because it violates the following Content Security Policy directive script-src 'self' 'unsafe-eval'. Either the unsafe-inline keyword, a hash or a nonce is required to enable inline execution.

I tried multiple links of stackoverflow, but unable to find any resolution. Does Chrome V3 allows inline script injection ? If not what's the alternative.

  • 1
    it's giving you a suggestion ... `Either the unsafe-inline keyword, a hash or a nonce is required to enable inline execution.` ... have you tried any one of these? – Jaromanda X Sep 09 '22 at 05:48
  • Yes adding unsafe-inline , again throwing exception saying 'content_security_policy.extension_pages': Insecure CSP value "'unsafe-inline'" in directive 'script-src'. – user2020718 Sep 09 '22 at 06:05
  • I take it `` is dynamic in nature, otherwise you'd simply inject code directly from the extension – Jaromanda X Sep 09 '22 at 06:10
  • So is there a solution for it ? – user2020718 Sep 09 '22 at 06:16
  • depends on what `` does I guess – Jaromanda X Sep 09 '22 at 06:18
  • Give us more information. What web pages are you injecting the javascript code into? Why does it need to be dynamic? And give us a link to the MV2 version of your extension (Github, etc.) – Thomas Mueller Sep 09 '22 at 06:22
  • Trying to override the gps api so as to pass our own gps info to the website. JS that I am injecting is not dynamic. It remains same. Do I need any code changes to make this work ? – user2020718 Sep 09 '22 at 06:35
  • See [this answer](https://stackoverflow.com/a/9517879) for alternatives. The only exact alternative that preserves both the timing and CSP exclusion is to use [registerContentScripts](https://stackoverflow.com/a/72607832) in the background script. – wOxxOm Sep 09 '22 at 06:49
  • @wOxxOm , I am sorry, but still can't understand how registerContentScripts can solve the issue ? How can I append a child node using this API. I followed https://stackoverflow.com/questions/9515704/use-a-content-script-to-access-the-page-context-variables-and-functions/9517879#9517879 but it's not working for me. – user2020718 Sep 09 '22 at 08:14
  • There's no need to add any nodes. You put the code into a file and register it as shown in my example. It will run in the page context automatically. – wOxxOm Sep 09 '22 at 13:25

0 Answers0