0

I'm working on what should be a simple Greasemonkey script to confirm that you want to close the window if you have a lengthy message typed.

I had a working version of this script a few years back, but the website it worked for has undergone changes, so I'm hoping to fix it. However, I can't even get a simple confirmation to work:

function confirmClose() {
    return 'You have a long message typed. Are you sure you want to close?';
}

window.addEventListener('beforeunload', confirmClose, true);

I'm positive the script is running on the pages it should, but whenever I attempt to close the window, I don't receive any confirmation.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Paul
  • 309
  • 1
  • 2
  • 15
  • Known bug in Firefox. http://stackoverflow.com/questions/5398772/firefox-4-onbeforeunload-custom-message – Bert Dec 23 '12 at 23:26

1 Answers1

1

As a security measure, Firefox no longer allows pages to set a custom message for the beforeunload dialog. So, the return statement doesn't have any effect when using addEventListener (which you should).

To stop a page from unloading, you need to use preventDefault() like so:

window.addEventListener ('beforeunload', confirmClose, false);

function confirmClose (zEvent) {
    zEvent.preventDefault ();
}

This will throw up the unalterable dialog:

Standard page-quit verification dialog


If you want to display a custom message, you can do so with an extra dialog like so:

window.addEventListener ('beforeunload', confirmClose, false);

function confirmClose (zEvent) {
    var doQuitPage = confirm (
        "You have a long message typed. Are you sure you want to close?"
    );
    if ( ! doQuitPage) {
        zEvent.preventDefault ();
    }
}

But note two important annoyances:

  1. If the user presses OK, then the page will exit with no further muss.
    But, if the user presses Cancel, then the Are you sure dialog will pop up and the user still must press Stay on Page.

  2. Per the HTML5 spec, future versions of Firefox might stop allowing confirm() during beforeunload events.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • 1
    This still isn't working for me. The lines I have `function confirmClose(evt) { evt.preventDefault(); } window.addEventListener('beforeunload', confirmClose, true);` – Paul Dec 24 '12 at 03:19
  • That works fine. Something else is going on. Try the code on a simpler page. Link to the target page. http://pastebin.com/ your actual complete script. – Brock Adams Dec 24 '12 at 03:40