javascript - How to execute a content script every time a page loads? -
i'm writing chrome extension provides content script page on github (i.e. url matching https://github.com/*
).
i'm trying log console each time page on github loads, so:
window.onload = function() { console.log("load"); };
this listener function executed first time github page loaded, if user navigates other pages on github there (by clicking on links or through other means), doesn't fire. why? :(
steps reproduce:
- open repository's page on github (example). should see message logged console.
- click on link on page. when new page loaded, no message logged. :(
how solve this?
it seems github uses ajax (along history.pushstate
) load parts of site, onload
fire when page loads, not when content loaded via ajax.
since github uses pushstate
change url when ajax content done loading, can detect when happens, , execute code. there isn't native event right fires when pushstate
used, there's little hack:
(function(history){ var pushstate = history.pushstate; history.pushstate = function(state) { if (typeof history.onpushstate == "function") { history.onpushstate({state: state}); } return pushstate.apply(history, arguments); } })(window.history);
so, run that, , then, instead of window.onload
, can do:
history.onpushstate = function () { console.log("load"); };
not of github page's load way (ajax + pushstate
), you'd have use both, window.onload
, history.onpushstate
.
also, should use window.addeventlistener('load', fn);
instead of window.onload
, since don't know if github's code overwriting window.onload
.
Comments
Post a Comment