I have read this question Is it possible to inject a javascript code that OVERRIDES the one existing in a DOM? and the solution works well most of time, but sometimes, seems JavaScript code in page will run first and then content_scripts.
This will make the 'OVVERRIDES' failed sometimes.
My test code as below:
//manifest.json
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["js_injector.js"],
"run_at": "document_start"
}
//js_injector.js
function injectJs(link) {
var scr = document.createElement('script');
scr.type="text/javascript";
scr.src=link;
document.documentElement.appendChild(scr);
}
injectJs(chrome.extension.getURL('my.js'));
//my.js
console.log("in my.js");
function foo() {
console.log("in my.js foo");
}
//test.html (view this page in chrome)
<html>
<script type="text/javascript">
console.log("I am here 1110");
foo()
console.log("I am here 1111");
</script>
</html>
Usually, I will get below logs:
in my.js my.js:114
I am here 1110 test.html:4
in my.js foo my.js:116
I am here 1111 test.html:6
But sometimes, below logs will be got:
I am here 1110 test.html:4
Uncaught ReferenceError: foo is not defined test.html:5
in my.js test.js:114
Seems the order to run code in pages and content scripts are random? And my purpose is let target pages run js apis that defines in content scripts. Does someone know how to fix it? Thanks!