I'm injecting a code into a webpage from contentscript using a classical V3 approach like so:
var s = document.createElement('script');
s.src = brs.runtime.getURL('injected.js');
console.log(s);
s.onload = function() {
this.remove();
};
(document.head || document.documentElement)
.appendChild(s);
I expect the injected.js to run before all other scripts in the page are executed, because I hook to Object.defineProperty function to intercept variables from the web page scripts. When I put breakpoints I see that first thing that is executed when I reload the page is contentscript and then injected.js and only then webpage script. However when I close the console magic happens. They just start executing in random order. I can't inject any traces into the webpage script, but I can clearly see it's being executed before the hook is in place, because the properties are not being intercepted by injected.js code as expcted (tested by putting a breakpoint), which means webpage scripts are being executed before the hook is in place, which means webpage scripts are being executed before injected.js. It is also not clear what causes the issue, the fact that contentscript runs in a sandbox environment and is executed "kind of" in parallel, or injected.js is being added to the page, but for some reason being executed after webpage scripts, which are loaded later.
In other words: MADNESS? THIS IS CHROME!!!
P.S.
If I turn my extension into a Tampermonkey user script it works perfectly. I can also actually use rules to redirect the request to script and modify it, getting the properties that way, but I don't want my users having to use Tampermonkey and I want to put the extension in chrome store, so it's easy to install, and we all know once you have funky things like declarativeNetRequest in your manifest and updateDynamicRules in your code, it's never being approved by chrome store.