Home > Web Front-end > JS Tutorial > How to Detect and Respond to URL Changes in JavaScript?

How to Detect and Respond to URL Changes in JavaScript?

Linda Hamilton
Release: 2024-10-28 18:10:30
Original
371 people have browsed it

How to Detect and Respond to URL Changes in JavaScript?

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);
};
Copy after login

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template