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 with MutationObserver in Greasemonkey?

DDD
Release: 2024-10-29 03:59:29
Original
413 people have browsed it

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

  1. Initialize the old URL:

    <code class="js">var oldHref = document.location.href;</code>
    Copy after login
  2. 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>
    Copy after login

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template