0

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");
            }
        });
}
Ahmad Sanie
  • 3,628
  • 2
  • 16
  • 52
Bhanu
  • 155
  • 2
  • 12
  • Your question is unclear. Explain your purpose cleary. What your want exactly? – Mohammad May 12 '16 at 10:54
  • i need to detect the back button hit of browser as well as in keyboard stroke.,. When i click on backbutton either on browser or keystroke, i need to check weather any dialog box is open..If open , close it and refresh the page – Bhanu May 12 '16 at 10:56

2 Answers2

1

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);
});
Cheezy Code
  • 1,565
  • 1
  • 11
  • 17
0

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

Community
  • 1
  • 1
aifrim
  • 527
  • 9
  • 17