Home >Web Front-end >JS Tutorial >How to Detect URL Changes After the Hash Symbol in JavaScript?

How to Detect URL Changes After the Hash Symbol in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 12:54:02691browse

How to Detect URL Changes After the Hash Symbol in JavaScript?

Detecting URL Changes in JavaScript After Hash Symbol

JavaScript offers ways to detect if a URL has changed, including the following options:

  • Onload Event:

    • The onload event is not triggered when the URL changes after the hash symbol.
  • Event Handler for URL:

    • There is no built-in event handler specifically for detecting URL changes.
  • Checking URL Every Second:

    • While constantly checking the URL every second may work, it's inefficient and can lead to performance issues.

Using the Navigation API (For Modern Browsers)

Major browsers now support the Navigation API, which provides a more efficient way to detect URL changes:

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

Custom Event for Older Browsers

For older browsers without the Navigation API, a custom event listener can be created by modifying the history object:

(() => {
    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"));
    });
})();

Now, you can listen for URL changes using the "locationchange" event:

window.addEventListener("locationchange", function () {
    console.log("location changed!");
});

The above is the detailed content of How to Detect URL Changes After the Hash Symbol 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