Home  >  Article  >  Web Front-end  >  How Can I Detect URL Changes After the Hash in JavaScript?

How Can I Detect URL Changes After the Hash in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 05:53:14118browse

How Can I Detect URL Changes After the Hash in JavaScript?

Detecting URL Changes After the Hash in JavaScript

When working with AJAX-based websites like GitHub, determining whether the URL has changed can be crucial. JavaScript allows for different methods to monitor URL changes.

Options for Detecting URL Changes:

  • onload Event: This event fires only when the page fully reloads, hence it's not suitable for detecting partial URL changes.
  • URL Event Handler: JavaScript does not provide a direct event handler for URL changes.
  • Regular URL Checks: Constantly checking the URL every second may be resource-intensive and impractical.

Improved Method: Navigation API (2024)

Modern browsers now support the Navigation API, which provides a more efficient way to detect URL changes. Here's how it works:

window.navigation.addEventListener("navigate", (event) => {
  console.log('location changed!');
});

Alternative Method (Pre-Navigation API)

If the Navigation API is not available, a custom approach can be employed using the following code:

(function () {
    let oldPushState = history.pushState;
    history.pushState = function pushState() {
        let ret = oldPushState.apply(this, arguments);
        window.dispatchEvent(new Event('pushstate'));
        window.dispatchEvent(new Event('locationchange'));
        return ret;
    };

    let oldReplaceState = history.replaceState;
    history.replaceState = function replaceState() {
        let ret = oldReplaceState.apply(this, arguments);
        window.dispatchEvent(new Event('replacestate'));
        window.dispatchEvent(new Event('locationchange'));
        return ret;
    };

    window.addEventListener('popstate', () => {
        window.dispatchEvent(new Event('locationchange'));
    });
})();

This solution modifies the history object to add functionality, allowing for the creation of custom event listeners, such as:

window.addEventListener('locationchange', () => {
    console.log('location changed!');
});

The above is the detailed content of How Can I Detect URL Changes After the Hash in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:My React Journey: Day 4Next article:My React Journey: Day 4