Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect URL changes (without window unload)

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.

like image 575
Keven Wang Avatar asked Aug 25 '13 00:08

Keven Wang


People also ask

How do I know if my URL has been changed?

You can use the popstate method to detect those URL changes and make UI changes as needed. window. addEventListener('popstate', function (event) { // The URL changed... });

Is Beforeunload deprecated?

Deprecated. Not for use in new websites.

What triggers unload event?

The unload event is fired when the document or a child resource is being unloaded.


2 Answers

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.

like image 136
Brock Adams Avatar answered Sep 22 '22 05:09

Brock Adams


If you're writing a Chrome extension, you can listen to the onUpdated event which is fired when a tab url is changed. More information here https://developer.chrome.com/extensions/tabs.html#event-onUpdated.

like image 35
Ryan Dao Avatar answered Sep 22 '22 05:09

Ryan Dao