Home  >  Article  >  Web Front-end  >  How Can You Detect Back Button Clicks in a Browser?

How Can You Detect Back Button Clicks in a Browser?

DDD
DDDOriginal
2024-10-22 14:02:02900browse

How Can You Detect Back Button Clicks in a Browser?

Detect Back Button Click in Browser

To track user navigation events, the window.onbeforeunload event listener can be employed. However, this event triggers not only when the back button is pressed but also during page refresh or reload.

Solution:

To resolve this issue, the following code utilizing the window.onload event can be used:

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle back/forward navigation here
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Handle hash change navigation here
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
}

This solution distinguishes between back navigation and other events like refresh and reloads, offering precise handling of back button clicks. It operates smoothly in browsers such as Chrome and Firefox.

The above is the detailed content of How Can You Detect Back Button Clicks in a Browser?. 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