Detecting URL Changes with Hash in JavaScript
Observing changes in a URL, including those after the hash symbol, is essential for applications using AJAX for page updates. JavaScript provides several options to track URL alterations.
Event Handlers
JavaScript offers event handlers that can be used to detect URL changes:
Manually Checking the URL
Polling the URL at regular intervals is a crude but reliable approach to detecting changes. However, it requires an ongoing timer and is computationally expensive.
Enhanced History API
Modern browsers support the Navigation API, which provides a dedicated "navigate" event. This event fires whenever the location changes, regardless of the cause (e.g., pushState, replaceState, hash change).
Polyfill for Legacy Browsers
For browsers that don't support the Navigation API, the following modified history object can be implemented:
(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 modification adds a custom "locationchange" event that triggers for all history operations (pushState, replaceState, popstate) and allows event listeners to be attached for detecting URL changes.
The above is the detailed content of How to Detect URL Changes, Including Hash Changes, in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!