admin管理员组

文章数量:1331230

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.

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.

Share edited Sep 23, 2013 at 1:50 Brock Adams 93.7k23 gold badges241 silver badges305 bronze badges asked Aug 25, 2013 at 0:10 Keven WangKeven Wang 1,2781 gold badge19 silver badges30 bronze badges 7
  • 1 Give the History API a shot. – Joseph Commented Aug 25, 2013 at 0:13
  • try searching for local storage – Charaf JRA Commented Aug 25, 2013 at 0:15
  • You might be looking for the beforeunload event coupled with the History API – Martin Jespersen Commented Aug 25, 2013 at 0:38
  • You want to use this in a popup window? Or using a greesemonkey script? Your missing some key information in your post. – Menelaos Commented Aug 25, 2013 at 0:46
  • 1 You've specifically said that you want to detect navigation on YouTube. In that case, see this answer to this question. – Rob W Commented Sep 23, 2013 at 13:44
 |  Show 2 more ments

2 Answers 2

Reset to default 4

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.

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./extensions/tabs.html#event-onUpdated.

本文标签: javascriptDetect URL changes (without window unload)Stack Overflow