admin管理员组

文章数量:1310420

Is there a way detect/catch the browser back button being pressed and in doing so ask them if they are sure about going back?

Building an application and it will soon be converted to an ajax based application and per requirements it's supposed to reset the application if a user goes 'back'...

I mainly want this to catch the accidental back button presses as I personally feel that if someone can't follow the directions that are given to them at the beginning of the application.... I'm not worried about their extra work.

If there isn't a way to do this is would the best solution be to launch the application in a new window/tab so that there is no history for it to go back to?

Is there a way detect/catch the browser back button being pressed and in doing so ask them if they are sure about going back?

Building an application and it will soon be converted to an ajax based application and per requirements it's supposed to reset the application if a user goes 'back'...

I mainly want this to catch the accidental back button presses as I personally feel that if someone can't follow the directions that are given to them at the beginning of the application.... I'm not worried about their extra work.

If there isn't a way to do this is would the best solution be to launch the application in a new window/tab so that there is no history for it to go back to?

Share Improve this question edited May 16, 2022 at 7:51 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Feb 26, 2012 at 6:08 JaredJared 6,0909 gold badges52 silver badges88 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

you can use onbeforeunload to detect back button or accidental page navigations:

window.addEventListener("beforeunload", function() {
     var ans = confirm("Are you sure?");
     if (ans) {
          //TODO: add your code here
     }
}, false);

to replace the current page in browser history you can use window.location.replace():

window.location.replace("yourNewURL");

You can also set the onbeforeunload function like this:

    window.onbeforeunload = function() {
       return "Are you sure you wish to leave?";
    };

本文标签: javascriptDetectWarn when back button is pressedStack Overflow