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

How to Detect User\'s Back Button Click in Browsers Without Browser Reload Interference?

Patricia Arquette
Release: 2024-10-22 14:41:48
Original
213 people have browsed it

How to Detect User's Back Button Click in Browsers Without Browser Reload Interference?

Detect User's Back Button Click in Browsers

When attempting to detect back button clicks, developers often rely on the window.onbeforeunload event listener. However, this event triggers not only for back button clicks but also for browser reloads, which can be misleading.

Detecting Back Button Clicks without Browser Reload Interference

To handle back button clicks without false positives, consider using a tailored approach:

  1. History Modification:

    • Upon page load, check if the history.pushState API is available.
    • If supported, push a random state onto the history using history.pushState.
    • Define an onpopstate event listener to handle back and forward button transitions.
  2. Hash-Based Approach:

    • If history.pushState is not supported, use the hash change event (window.onhashchange).
    • Set an initial hash value, and upon hash changes, check for a non-random hash value.
    • Use a flag to ensure only user-initiated hash changes trigger the back button logic, ignoring browser reloads.

Implementation

<code class="javascript">window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle back button click here
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Handle back button click here
            }
            else {
                ignoreHashChange = false;
            }
        };
    }
}</code>
Copy after login

Compatibility

This approach has been reported to work effectively in Chrome and Firefox.

The above is the detailed content of How to Detect User\'s Back Button Click in Browsers Without Browser Reload Interference?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!