Home >Web Front-end >JS Tutorial >How to Execute Code When the Page\'s URL Changes with MutationObserver in Greasemonkey?
How to Execute Code When the Page's URL Changes
In the context of Greasemonkey scripting, it becomes necessary to respond to changes in a page's URL (location.href) efficiently. To achieve this without introducing timeouts or polling, consider leveraging the MutationObserver API.
Solution Using MutationObserver
Initialize the old URL:
<code class="js">var oldHref = document.location.href;</code>
Attach a MutationObserver to the body element:
<code class="js">window.onload = function() { var bodyList = document.querySelector('body'); var observer = new MutationObserver(function(mutations) { if (oldHref != document.location.href) { oldHref = document.location.href; /* Execute your code here */ } }); var config = { childList: true, subtree: true }; observer.observe(bodyList, config); };</code>
Latest JavaScript Specification
For modern browsers that support the latest JavaScript specification, use the following simplified syntax:
<code class="js">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; /* Execute your code here */ } }); observer.observe(body, { childList: true, subtree: true }); }; window.onload = observeUrlChange;</code>
By utilizing MutationObserver, you can effectively capture URL changes and trigger custom code execution without resorting to unreliable polling techniques.
The above is the detailed content of How to Execute Code When the Page\'s URL Changes with MutationObserver in Greasemonkey?. For more information, please follow other related articles on the PHP Chinese website!