"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to reliably detect the browser back button and distinguish back actions within the page?

How to reliably detect the browser back button and distinguish back actions within the page?

Posted on 2025-04-17
Browse:144

How Can We Reliably Detect Browser Back Button Presses and Differentiate Them from In-Page Back Button Actions?

Implementing Cross-Browser Browser Back Button Detection

Detecting Back Button Press Events

Determining whether the user has pressed the browser back button poses a challenge. Many propose using the window.onhashchange function, but it also responds to in-page back buttons, adversely affecting the user experience.

Managing In-Page Back Button Functionality

For single-page applications utilizing hash navigation, it's crucial to control the behavior of in-page back buttons. To do so, employ an array (window.location.lasthash) to store previous hashes as the user navigates the interface.

Distinguishing Browser Back Button from In-Page Back Button

Conventional methods like window.onbeforeunload and window.onmousedown proved ineffective for distinguishing browser back button clicks. Instead, a flag variable toggled by the document's onmouseover (when mouse hovers over the document) and onmouseleave (when mouse exits the document) was devised.

Utilizing the Detection Mechanism

Modify window.onhashchange to incorporate this logic:

window.onhashchange = function() {
    if (window.innerDocClick) {
        // In-page mechanism triggered the hash change
    } else {
        if (window.location.hash != '#undefined') {
            // Browser back button clicked
            goBack();
        }
    }
}

Preventing Backspace from Mimicking Back Button

To prevent backspace from triggering the back button event, implement the following script:

$(function(){
    var rx = /INPUT|SELECT|TEXTAREA/i;

    $(document).bind("keydown keypress", function(e){
        if( e.which == 8 ){ // 8 == backspace
            if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
                e.preventDefault();
            }
        }
    });
});

In summary, by utilizing the document's hover events, one can effectively differentiate between browser back button clicks and in-page back button usage, allowing for precise control of back button functionality.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3