I'm migration my extension from V2 to V3. Now all is working fine except for one thing. In my V2 version I did
const actualCode = '(' + function () { 'console.log("demo");' } + `)();`;
const script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.remove();
Note that the console.log("demo") is a simplification of what I need to inject :)
I need to inject some javascript for my chrome-extension-magic to take place.
Now, in V3 this doesn't work anymore. I get the following error in my devtools-console
content.js:23114
Refused to execute inline script because it violates the following
ContentSecurity Policy directive: "script-src 'self'". Either the
'unsafe-inline' keyword, a hash ('sha256-tN52+5...6d2I/Szq8='), or a nonce
('nonce-...') is required to enable inline execution.
In the migration guide I noticed this section
"content_security_policy": {
"extension_pages": "...",
"sandbox": "..."
}
but there is not much description there, so this is magic to me. So I hope someone know can help me with this?
Refer to Use a content script to access the page context variables and functions
Since content scripts are executed in an "isolated world" environment,
we can't do some special dom operations in content_script js.
This example will show you how to inject inject.js to web page before document start:
// document_start.js
var s = document.createElement('script');
s.src = chrome.runtime.getURL('inject.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
manifest.json example for ManifestV3
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["document_start.js"],
"run_at": "document_start" //default document end
}
]
"web_accessible_resources": [{
"resources": ["inject.js"],
"matches": ["<all_urls>"]
}]