Home >Web Front-end >JS Tutorial >How Can We Reliably Detect Browser Back Button Presses and Differentiate Them from In-Page Back Button Actions?

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

Susan Sarandon
Susan SarandonOriginal
2024-12-10 18:19:15570browse

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.

The above is the detailed content of How Can We Reliably Detect Browser Back Button Presses and Differentiate Them from In-Page Back Button Actions?. 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