Home > Web Front-end > JS Tutorial > body text

How to Detect URL Changes, Including Hash Changes, in JavaScript?

Linda Hamilton
Release: 2024-11-25 08:35:22
Original
636 people have browsed it

How to Detect URL Changes, Including Hash Changes, in JavaScript?

Detecting URL Changes with Hash in JavaScript

Observing changes in a URL, including those after the hash symbol, is essential for applications using AJAX for page updates. JavaScript provides several options to track URL alterations.

Event Handlers

JavaScript offers event handlers that can be used to detect URL changes:

  • onload: This event is not suitable for detecting URL changes after the initial page load.
  • hashchange: This event triggers only when the part after the hash symbol changes, but not for other URL modifications.

Manually Checking the URL

Polling the URL at regular intervals is a crude but reliable approach to detecting changes. However, it requires an ongoing timer and is computationally expensive.

Enhanced History API

Modern browsers support the Navigation API, which provides a dedicated "navigate" event. This event fires whenever the location changes, regardless of the cause (e.g., pushState, replaceState, hash change).

Polyfill for Legacy Browsers

For browsers that don't support the Navigation API, the following modified history object can be implemented:

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

This modification adds a custom "locationchange" event that triggers for all history operations (pushState, replaceState, popstate) and allows event listeners to be attached for detecting URL changes.

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