简体   繁体   中英

how to detect back button of browser in jquery and if any dialogue is open close it?

What i want to do is, if i press back button when any other pop up is opened , i should close that pop up and reload the page .

i have tried below. but it is only taking the keyboard backbutton but not browser back button. can any one help me to solve this

$(document).ready(function() {

     $(document).bind("keydown keypress", function(e){
            if( e.which == 8 ){ // 8 == backspace
                alert("back button");
            }
        });
}

Code snippet for detecting browser back and closing the popup.

var path = 'pageURL';
history.pushState(null, null, path + window.location.search);
window.addEventListener('popstate', function (event) {
    //Code to close the pop up
    history.pushState(null, null, path + window.location.search);
});

If you want it to stop navigating to this:

$(document).bind("keydown", function(e) {

    // if a object has focus
    // inputs, textarea, etc.
    if($(":focus").length != 0) {
        return;
    }

    // else don't allow the press
    if(e.keyCode == 8) {
        parent.postMessage("message");
        window.close();
        e.preventDefault();
    }
});

For me it captures and disables the browser back. And you can comunicate between windows with postMessage

More info on communicating between windows. https://davidwalsh.name/window-iframe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM