Home > Article > Web Front-end > How to Reliably Detect URL Changes in JavaScript?
Detecting URL Changes in JavaScript
To track URL changes in JavaScript, it's crucial to identify a reliable method. While the onload event is not suitable, there are several viable options.
1. Hash Change Event:
This event triggers only when the URL portion after the # symbol changes. It's limited to hash-related alterations.
2. Popstate Event:
This event occurs when the browser's history navigation buttons (e.g., back and forward) are used or when the URL changes via pushState or replaceState methods. However, it may not work in all cases.
3. Custom Locationchange Event (Recommended):
To ensure comprehensive URL change detection, a custom event listener, 'locationchange,' can be implemented. This involves modifying the history object to trigger custom events for all history state changes (i.e., pushState, replaceState, and popstate).
Implementation:
// Create a custom locationchange event window.addEventListener('locationchange', () => { console.log('Location changed!'); }); // Modify history object to trigger custom events (() => { 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')); }); })();
By employing this custom event, you can effectively detect any URL change, regardless of whether it occurs via hash, pushState, or replaceState. This method provides a comprehensive solution for monitoring URL changes in JavaScript applications.
The above is the detailed content of How to Reliably Detect URL Changes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!