Home >Web Front-end >JS Tutorial >How Can I Reliably Detect Browser Back Button Clicks and Enforce In-Page Navigation?

How Can I Reliably Detect Browser Back Button Clicks and Enforce In-Page Navigation?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 10:15:11557browse

How Can I Reliably Detect Browser Back Button Clicks and Enforce In-Page Navigation?

Cross-Browser Technique for Detecting Browser Back Button Clicks and Enforcing In-Page Navigation

Detecting the browser's back button click and enforcing the use of an in-page navigation system using a hashtag (#) system can be challenging.

Browser Back Button Detection

The conventional approach of using window.onhashchange alone is not reliable, as it also triggers when in-page elements change the hash. To address this, a novel technique utilizing document.onmouseover, document.onmouseleave, and a boolean flag (window.innerDocClick) is employed. When the user's mouse enters the document area, window.innerDocClick is set to true, and when it leaves, it is set to false. This allows for the following window.onhashchange handler:

window.onhashchange = function() {
    if (window.innerDocClick) {
        window.innerDocClick = false;
    } else {
        if (window.location.hash != '#undefined') {
            goBack();
        } else {
            history.pushState("", document.title, window.location.pathname);
            location.reload();
        }
    }
}

In-Page Back Button Enforcement

To control back navigation solely through the in-page back button, a history array (window.location.lasthash) is utilized to store previous hashes as the user progresses through the interface. An in-page back button function (goBack) uses this array to navigate to the previous page.

function goBack() {
    window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
    window.location.lasthash.pop();
}

Suppressing Backspace Key

To prevent the user from using the backspace key to trigger the back button, the following code snippet can be added:

$(function(){
    /*
     * this swallows backspace keys on any non-input element.
     * stops backspace -> back
     */
    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();
            }
        }
    });
});

The above is the detailed content of How Can I Reliably Detect Browser Back Button Clicks and Enforce In-Page Navigation?. 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