Detecting URL Changes in JavaScript After Hash Symbol
JavaScript offers ways to detect if a URL has changed, including the following options:
Onload Event:
Event Handler for URL:
Checking URL Every Second:
Using the Navigation API (For Modern Browsers)
Major browsers now support the Navigation API, which provides a more efficient way to detect URL changes:
window.navigation.addEventListener("navigate", (event) => { console.log("location changed!"); });
Custom Event for Older Browsers
For older browsers without the Navigation API, a custom event listener can be created by modifying the history object:
(() => { let oldPushState = history.pushState; history.pushState = function pushState() { let ret = oldPushState.apply(this, arguments); window.dispatchEvent(new Event("pushstate")); window.dispatchEvent(new Event("locationchange")); return ret; }; let oldReplaceState = history.replaceState; history.replaceState = function replaceState() { let ret = oldReplaceState.apply(this, arguments); window.dispatchEvent(new Event("replacestate")); window.dispatchEvent(new Event("locationchange")); return ret; }; window.addEventListener("popstate", () => { window.dispatchEvent(new Event("locationchange")); }); })();
Now, you can listen for URL changes using the "locationchange" event:
window.addEventListener("locationchange", function () { console.log("location changed!"); });
The above is the detailed content of How to Detect URL Changes After the Hash Symbol in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!