2

I'm writing a Chrome extension that provides a content script to any page on GitHub (i.e. any URL matching https://github.com/*).

I'm simply trying to log something to the console each time a page on GitHub loads, like so:

window.onload = function() {
  console.log("LOAD");
};

This listener function is executed the very first time a GitHub page is loaded, but if the user navigates to other pages on GitHub from there (by clicking on links or through other means), it doesn't fire. Why? :(

Steps to reproduce:

  1. Open any repository's page on GitHub (example). You should see the message logged to the console.
  2. Click on any link on that page. When the new page is loaded, no message is logged. :(

How do I solve this?

XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151

1 Answers1

2

It seems that GitHub uses AJAX (along with history.pushState) to load some parts of the site, so onload will fire only when the page truly loads, but not when content is loaded via AJAX.

Since GitHub uses pushState to change the URL when AJAX content is done loading, you can detect when that happens, and execute your code. There isn't actually a native event right now that fires when pushState is used, but there's this 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, and then, instead of window.onload, you can do:

history.onpushstate = function () {
    console.log("LOAD");
};

Not ALL of GitHub page's load this way (AJAX + pushState), so you'd have to use both, window.onload and history.onpushstate.

Also, you should use window.addEventListener('load', fn); instead of window.onload, since you don't know if GitHub's code could be overwriting window.onload.

Community
  • 1
  • 1
  • 1
    This answer requires special adaptation to Chrome Extension case. Since a content script [executes in a separate context](https://developer.chrome.com/extensions/content_scripts#execution-environment), modifying the `pushState` will not affect the page's copy of it. You need to [inject the above code in the page's context](http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script). – Xan Apr 25 '15 at 09:42