1

When the user closes the tab or refreshes the page, the site must display a popup to confirm this. I tried this code:

window.onbeforeunload = function (e) {
    return confirm("Are you sure you want to leave this page?");
};

This didn't work in either firefox or chrome. In firefox no popup came up. And in chrome the default one didn't get overridden either. I even tried using the following code but to no avail:

window.onbeforeunload = function (e) {
    var dialogText = 'Are you sure about this?';
    e.returnValue = dialogText;
    return dialogText;
};

How do I solve this issue? Any code snippets would be helpful. Thank you.

Kartik Shenoy
  • 308
  • 3
  • 14
  • Possible duplicate of [How to create popup window when browser close](http://stackoverflow.com/questions/4067796/how-to-create-popup-window-when-browser-close) – Matthijs Aug 27 '16 at 18:54
  • Possible duplicate of [Trying to detect browser close event](http://stackoverflow.com/questions/20853142/trying-to-detect-browser-close-event) – Bobulous Aug 27 '16 at 18:54
  • This is already answered in this similar post http://stackoverflow.com/questions/10310177/showing-a-jquery-popup-before-browser-window-closes – Rodney Zanoria Aug 27 '16 at 18:55
  • I've already explained it here: http://stackoverflow.com/questions/39128680/firefox-doesnt-display-any-warning-dialog-for-window-beforeunload-event/39128839#39128839 –  Aug 27 '16 at 18:57
  • Possible duplicate of [Is it possible to display a custom message in the beforeunload popup?](http://stackoverflow.com/questions/38879742/is-it-possible-to-display-a-custom-message-in-the-beforeunload-popup) – Dekel Aug 27 '16 at 21:49

3 Answers3

2

I found this snippet on the internet:

window.onbeforeunload = function (e) {
        return "Please click 'Stay on this Page' if you did this unintentionally";
    };

This is working perfectly as required. I found out that you actually don't need to add any confirm call. If you just return a string, this will prompt the browser to confirm leaving the page. Most commercial browsers have this functionality supported by default.

Kartik Shenoy
  • 308
  • 3
  • 14
1

From Firefox's documentation:

To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with.

You cannot show pop-up if user didn't interacted with the page before.

0

Starting with Firefox 4, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved."

-- from Mozilla Developer Docs

Will.Ling
  • 21
  • 6