Detect URL changes (without window unload)

ajax, google-chrome-extension, javascript, url

Solution

For AJAX-driven pages that use the `history` API (most of them, including YouTube), you can splice into `history.pushState`.

For Chrome, the old url will be in the `spf-referer` property. (Also, the `location.href` will still be set to the old URL while pushState is firing, too.)

So code like this will work:

var H               = window.history;
var oldPushState    = H.pushState;
H.pushState         = function (state) {
    if (typeof H.onpushstate == "function") {
        H.onpushstate ({state: state} );
    }
    return oldPushState.apply (H, arguments);
}
window.onpopstate = history.onpushstate = function (evt) {
    console.log ("Old URL: ", evt.state["spf-referer"]);
}

Note that, because you need to override the target page's `pushState` function, you must inject this code from your content script.

Problem

I want to add a listener to "before URL change" event, with access to the old URL. `window.onbeforeunload` does not fire if the page does not reload (AJAX driven pages). This happens on YouTube video pages, when you click on another video in the right navigation column, for example. I have read this post, which polls `window.location`. But this does not capture the old URL. This is for a Chrome extension. I'm looking for a way to detect before URL change in javascript.

Original source

Related problems