Home > Article > Web Front-end > How Can I Detect URL Changes After the Hash in JavaScript?
Detecting URL Changes After the Hash in JavaScript
When working with AJAX-based websites like GitHub, determining whether the URL has changed can be crucial. JavaScript allows for different methods to monitor URL changes.
Options for Detecting URL Changes:
Improved Method: Navigation API (2024)
Modern browsers now support the Navigation API, which provides a more efficient way to detect URL changes. Here's how it works:
window.navigation.addEventListener("navigate", (event) => { console.log('location changed!'); });
Alternative Method (Pre-Navigation API)
If the Navigation API is not available, a custom approach can be employed using the following code:
(function () { 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')); }); })();
This solution modifies the history object to add functionality, allowing for the creation of custom event listeners, such as:
window.addEventListener('locationchange', () => { console.log('location changed!'); });
The above is the detailed content of How Can I Detect URL Changes After the Hash in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!