How to Trigger an Event When the URL Changes
When developing Greasemonkey scripts for websites that periodically modify the window.location.href, it's often necessary to perform specific actions in response to these URL changes. However, utilizing polling or timeouts as potential solutions can be inefficient.
To avoid such issues, we present a highly effective method that makes use of the MutationObserver API. By monitoring changes within the body element, this script can effectively detect URL modifications and provide access to the modified document's DOM:
var oldHref = document.location.href; window.onload = function() { var bodyList = document.querySelector('body'); var observer = new MutationObserver(function(mutations) { if (oldHref != document.location.href) { oldHref = document.location.href; /* Insert your code here */ } }); var config = { childList: true, subtree: true }; observer.observe(bodyList, config); };
Alternatively, if you prefer a more concise and modern approach, you can use the following script, which leverages the latest JavaScript specification:
const observeUrlChange = () => { let oldHref = document.location.href; const body = document.querySelector('body'); const observer = new MutationObserver(mutations => { if (oldHref !== document.location.href) { oldHref = document.location.href; /* Insert your code here */ } }); observer.observe(body, { childList: true, subtree: true }); }; window.onload = observeUrlChange;
This method allows you to attach your desired functionality to the event triggered when the URL changes, providing access to the modified document's DOM.
The above is the detailed content of How to Detect and Respond to URL Changes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!