URL change detection (without window unloading)

I want to add a listener to the "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, for example, when you click on another video in the right navigation column.

I read this post which will poll window.location . But this does not reflect the old URL.

This is for the Chrome extension. I am looking for a way to detect before changing the url in javascript.

+5
javascript url ajax google-chrome-extension
source share
2 answers

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

For Chrome, the old URL will be in the spf-referer property. (In addition, location.href will still be set to the old URL, while pushState will also start.)

So, this code 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"]); } 

Please note that since you need to override the pushState landing page pushState , you must paste this code from your script content.

+4
source share

If you write a Chrome extension, you can listen for the onUpdated event, which fires when the tab URL changes. More information here https://developer.chrome.com/extensions/tabs.html#event-onUpdated .

+2
source share

All Articles