简体   繁体   中英

How to disable browser feature

I am developing a project where user gets a conformation page. I want user not to click back or close tab or reload. Now either I need to disable the browser features or get back button,tab close event, or reload event to java script so that I could take the needed steps to prevent my data to get lost. I have used this:

window.onbeforeunload = function() 
{
     return "Try This"; 
};

But this get called even when I click a button that redirects the page.

If you just want to have the alert, understanding that the user is ultimately in control and can bypass your alert, then do what you're doing but use a flag that disables it when you're navigating and don't want the alert. Eg:

var warnWhenLeaving = true;
window.onbeforeunload = function() {
    if (warnWhenLeaving) {
        return "your message here";
    }
};

then in a click handler on the link/button/whatever that moves the user on that you don't want this to pop up on:

warnWhenLeaving = false;

In a comment you asked:

can i know that what user has clicked when alert is generated with this function. That is can i know what user has clicked (leave this page/stay on page)

The answer is: Sort of , but not really; you're almost certainly better off not trying to.

But: If you see your onbeforeunload function run, then you know the user is leaving the page and the browser is likely to show them your message. The browsers I'm familiar with handle the popup like an alert : All JavaScript code on the page is blocked while the popup is there. So if you schedule a callback via setTimeout , you won't get the callback if they leave and you will if they stay:

window.onbeforeunload = function() {
  if (warnWhenLeaving) {
    setTimeout(function() {
      display("You stayed, yay!");
    }, 0);
    return "No, don't go!";
  }
};

Live Example

So in theory, if you get the callback, they stayed; if you see an unload event, they left. (Note that there are very few things you can do in an unload event.)

I've tried that on current Chrome, current Firefox, IE8, and IE11: It works on all of those. Whether it will work in the next release of any of them is anybody's guess. Whether it works reliably on mobile browsers is something you'd have to test, and again could change.

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