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

How to Reliably Detect URL Changes in JavaScript?

Susan Sarandon
Release: 2024-11-12 09:57:02
Original
1067 people have browsed it

How to Reliably Detect URL Changes in JavaScript?

Detecting URL Changes in JavaScript

To track URL changes in JavaScript, it's crucial to identify a reliable method. While the onload event is not suitable, there are several viable options.

1. Hash Change Event:

This event triggers only when the URL portion after the # symbol changes. It's limited to hash-related alterations.

2. Popstate Event:

This event occurs when the browser's history navigation buttons (e.g., back and forward) are used or when the URL changes via pushState or replaceState methods. However, it may not work in all cases.

3. Custom Locationchange Event (Recommended):

To ensure comprehensive URL change detection, a custom event listener, 'locationchange,' can be implemented. This involves modifying the history object to trigger custom events for all history state changes (i.e., pushState, replaceState, and popstate).

Implementation:

// Create a custom locationchange event
window.addEventListener('locationchange', () => {
    console.log('Location changed!');
});

// Modify history object to trigger custom events
(() => {
    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

By employing this custom event, you can effectively detect any URL change, regardless of whether it occurs via hash, pushState, or replaceState. This method provides a comprehensive solution for monitoring URL changes in JavaScript applications.

The above is the detailed content of How to Reliably Detect 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