Datin
Datin

Reputation: 53

How to run JavaScript snippet right before onload event(Google Chrome Extension)

What I'm trying to do is write a Chrome extension that inserts a snippet of Javascript that will fire after all the Javascript code on the page has run, but before the onload event fires. (There is some code on the page that has an event listener for the onload event). I've tried all that I've thought of for my extension, but I haven't found a consistent way to do this with a Google Chrome Extension.

I've tried setting the run_at value to both "document_start" and "document_end", along with appending this snippet to both the head and the body, both as a <script></script> with inner html and a <script></script> with a src pointing to a file in the extension. Nothing consistently works.

Has anybody had any luck with this or any thoughts on how to proceed?


UPDATE!

I've made some progress, but now I've hit another snag. I have the extension set to run_at document_start, and it is always firing before the script is loaded. Then I add an event listener for the event DOMContentLoaded, then send a request to my background page (to get the currently selected options so I know how to modify the script on the page).

The issue now is that sometimes, the event fires before I receive my response from the background page. When I receive my response before DOMContentLoaded, everything works. Since this is asynchronous though, I haven't found a way to somehow force a wait for this response.

Does anybody have any thoughts of how to proceed?

Upvotes: 4

Views: 4232

Answers (2)

user479870
user479870

Reputation:

I haven't tried but using the defer attribute should work.

http://dev.w3.org/html5/spec-author-view/scripting-1.html#attr-script-defer

It works in WebKit, but only since last month so it'll take a while until it reaches Chrome stable.

http://webkit.org/blog/1395/running-scripts-in-webkit/

You can try Chrome Canary or a recent Chromium snapshot.

http://tools.google.com/dlpage/chromesxs
http://build.chromium.org/buildbot/snapshots/

It might also require setting a HTML5 doctype.

http://www.w3.org/TR/html5-diff/#doctype

Upvotes: 0

Ed.C
Ed.C

Reputation: 798

One naive solution would be to put your script just right before you close the body tag. In that way you are sure that all the scripts are loaded and that no onLoad has been called yet

Upvotes: 1

Related Questions