1

I have a confirm box on beforeload event - the code is as follows:

window.onbeforeunload = function(){
            //alert('leaving ... ' + is_edited );

            if (is_edited == true) {
                return confirm('Are you sure you want to navigate away from this page? \n\n Press OK to continue, or Cancel to stay on the current page.');
            }

        };

The problem is that - the confirm alert is showing twice. I have searched on stackoverflow and got many questions about this issue. But mine is somewhat different. It is not the same confirm alert showing twice. For FF the message is same but for Crome in second confirm box the message is false.

Thanks in advance.

Himadri
  • 13
  • 1
  • 3

2 Answers2

1

The "onbeforeunload" handler is supposed to return a string. Whether the string will be shown to the user or not is up to the browser.

Your function returns the result of the "confirm()" call, a boolean. Firefox 4 does not show the returned string from the "beforeunload" handler, while other browsers still do. Thus your function puts up a "Confirm" box, gets the result, and returns it. The browser then puts up the "beforeunload" confirmation, which in the case of some browsers will include the stringified value returned from your handler (either "true" or "false").

Here is the Mozilla documentation for the event and its handler.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • What do you mean by `The browser then puts up the "beforeunload" confirmation`? What I should do to show just one confirm box? – Himadri May 25 '11 at 05:10
  • What you should do is **not** do the "confirm()" in the "beforeunload" handler. The way the "beforeunload" handler works is pretty strange. All it can do is return a string. The browser **might** display that string to the user, or it might not - it's out of your control (for security/anti-spam reasons). – Pointy May 25 '11 at 12:33
0

It's better for you to use jQuery here for cross browser functionality.

jQuery UI Dialog OnBeforeUnload

Community
  • 1
  • 1
Sreekumar P
  • 5,900
  • 11
  • 57
  • 82
  • Ok, it works for me. Now I am getting just one confirm box. But the issue is what @Pointy says. FF and other browsers return different strings for different browsers. Can you suggest the solution? – Himadri May 25 '11 at 05:31