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
Release: 2024-11-12 12:54:02
Original
676 people have browsed it

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

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

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

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

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!

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