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.
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... });
Deprecated. Not for use in new websites.
The unload event is fired when the document or a child resource is being unloaded.
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.com/extensions/tabs.html#event-onUpdated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With