Home > Web Front-end > JS Tutorial > How to Detect Changes in `location.href` Using MutationObserver in Greasemonkey Scripts?

How to Detect Changes in `location.href` Using MutationObserver in Greasemonkey Scripts?

DDD
Release: 2024-10-27 20:30:30
Original
392 people have browsed it

How to Detect Changes in `location.href` Using MutationObserver in Greasemonkey Scripts?

Listening for Location.href changed events

When writing Greasemonkey scripts, sometimes you need to perform certain operations when the website modifies location.href . This article describes a way to respond to this change using DOM mutation observers instead of time-consuming timeouts and polling.

Solution

<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;
            // 执行相关的操作
        }
    });
    
    var config = {
        childList: true,
        subtree: true
    };
    
    observer.observe(bodyList, config);
};</code>
Copy after login

This script uses a DOM mutation observer to listen for changes throughout the document, including changes within the body element. When a location.href change is detected, it will trigger the observer callback function, where you can perform whatever actions you want.

With latest JavaScript specs

<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;
      // 执行相关的操作
    }
  });
  observer.observe(body, { childList: true, subtree: true });
};

window.onload = observeUrlChange;</code>
Copy after login

This script uses the latest JavaScript specs with ES6 arrow functions and the observe method. It is equivalent to the above script and provides a cleaner way to listen for location.href changes.

The above is the detailed content of How to Detect Changes in `location.href` Using MutationObserver in Greasemonkey Scripts?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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