Let's say my Chrome extension wants to work with a page containing the following html:
<!DOCTYPE html>
<html> <head> <script>
var foo = Math.random();
function bar(e) {
console.log(e + '_123');
}
</script> </head>
<body> Baz </body></html>
Inside my extension I want
- read generated value of
foo
- run
bar
as if it was runned by page native script.
My manifest.json
is
{
"manifest_version": 3,
"name": "Sample ext",
"version": "1.0.0",
"permissions": ["activeTab"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
...and content.js
is:
window.addEventListener('load', function() {
console.log(window.foo);
window.bar('arg');
});
I thought that the script specified in content_scripts
is injected into the page as if it were in its code initially.
Obviously, this is not the case: content.js
and the page have different window
objects:
It seems that content.js
(although it has access to DOM) is executed in some kind of sandbox environment.
Is there a way to get past this limitation?