I'm creating a Chrome Extension which modifies a script served by the server (which I have no control over) to add new functionality to the website, and I had the following idea:
- Block the original script via WebRequest, webRequestBlocking.
- Send the url of the blocked script to a script injected into the page.
- GET this url from the page's script.
- Edit a part of the code (string).
- Eval the string.
(Another working way is to redirect it to a local modified script return { redirectUrl: chrome.extension.getURL("modified.js") };
, inside the Chrome Extension folder, but then it's impossible to modify it on the fly, that's why I want to eval a modified script)
When I try to eval the string in the 5th step, it says: ...'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'nonce-DFX4zDtBDF32343LjE2DFKMs' 'self' https://website.com"
.
I've tried to use webRequest.onHeadersReceived
to see if I could alter CSP headers (as some answers suggested: Edit Content Security Policy in onHeadersReceived), but there is no "content-security-policy" header.
I can see a Content Security Policy meta tag (I've omitted everything except 'script-src'):
<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-DFX4zDtBDF32343LjE2DFKMs' 'self' https://website.com; base-uri 'none';">
From this answer (https://stackoverflow.com/a/27324485/10364842), Chrome Extensions cannot override CSP of Web pages. But someone replies: I know this is incredibly old, but I came across it while trying to inject Artoo.js into a page. The chrome extension does indeed allow you to modify the page you're looking at and let any content through.
Eval works in the content script, but I need to execute the script in the page's context, because it depends on the global scope.
I'm wondering if it's possible to alter CSP of a Web page through a Chrome Extension, or if there is any other way to accomplish this solely via a Chrome extension?