Chrome extension run at doc start

2019-08-01 21:44发布

问题:

I have a script that I want to be injected into the document BEFORE load. I.E; it should function as if

<script..>MYSCRIPT HERE</script>

<html>
.
.

I have made a script in chrome that executes correctly (I can alert(0) etc) but, it runs in different environment which is not what I want. I want it to run in the SAME environment as page.

Earlier, I had used a trick where in the startup script I had used

window.location="javascript:<MY SCRIPT HERE>"

which effectively changes the execution environment but for the past few days it isn't working. I think its a chrome bug fix. Is there any other workaround for this? Note: I can't add script tags dynamically to the page in the startup script because the document.body etc are unavailable.

I would like to provide you more details of why I need this and my previous solution. HTML Page which I don't have control over:

.
.
<script>
function a(){//DOSOMETHING}
</script>
.
.
<script>
a(); <<------ I DONT WANT TO CALL THIS
</script>

Precious solution: Startup javascript contains

window.location='javascript:const a=function(){};';<<-CONST used!!

^^That will force error of re-declaration of 'a' when the page actually loads, hence, when a() is called, nothing happens. (clever, right? -_-)

But now, I realized when I do window.location="js:..", even that runs in separate env!

Help! :)

回答1:

You should be able to inject script into the page's JavaScript context by adding a script tag via your content script. In other words, your script could be injected at document_idle, and execute something like:

var s = document.createElement('script');
s.textContent = 'const a = function () {};';
document.documentElement.appendChild(s);

That script tag would be executed in the context of the page, not in the context of your script, and should allow you to achieve the result you're looking for.

Documentation for content scripts in general is available at https://developer.chrome.com/extensions/content_scripts



回答2:

Chrome probably has a bug in the current build as PAEz pointed out. But yes, a lot of insight on how things can be injected into "document" using chrome extension. Thanks Mike for the post. Will keep that in mind the next time I'm injecting using greesemonkey or something :)