Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onbeforeunload Message Appears Twice (Internet Explorer)

I have the following script on my ASP.NET web page to warn the user when they are navigating away from a page with unsaved changes.

$(document).ready(function() {
    $('input:not(:button,:submit),textarea,select').change(function () {
        window.onbeforeunload = function () {
            return 'Changes made to this page have not been saved!';
        }
    });
});

This works just as intended except for some problems when the user is using Internet Explorer and attempts to navigate away using a link like this one.

<div onclick="window.location=&#39;http://www.domain.com&#39;;">Text</div>

If the user selects "Stay on this page", the message box appears twice. And then if they select "Stay on this page" the second time, the debugger highlights the link above with the message:

Microsoft JScript runtime error: Unspecified error.

This problem appears to be specific to Internet Explorer. Searching the Web, I've been able to find numerous references to what seem like related bugs, incredibly going back several versions of Internet Explorer. Yet, I've unable to find any comment from Microsoft or a reasonable fix. Here are a few of the links I've found that appear related.

  1. http://forums.asp.net/t/1199756.aspx/1
  2. Why is my onbeforeunload handler causing an "Unspecified error" error?
  3. http://www.telerik.com/community/forums/aspnet-ajax/tabstrip/cancel-on-onbeforeunload-in-ie-6-7-create-js-unspecified-error.aspx
  4. http://scottonwriting.net/sowblog/archive/2005/04/19/163068.aspx
  5. http://www.techtalkz.com/internet-explorer/116662-onbeforeunload-dialog-cancel-button-when-window-location-href-bug.html
  6. http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14213927
  7. http://www.webmasterkb.com/Uwe/Forum.aspx/jscript/4321/IE7-and-onbeforeunload
  8. http://www.bigresource.com/ASP-Javascript-Unspecified-Error-BHoy7ptS.html
  9. https://web.archive.org/web/20210417082636/http://www.4guysfromrolla.com/articles/042005-1.aspx

Can anyone suggest a workaround? Doesn't look like Connect is accepting IE bug reports. I'm using IE9

like image 307
Jonathan Wood Avatar asked Dec 12 '22 10:12

Jonathan Wood


1 Answers

We ran into the same issue in IE11.

It turns out that assigning window.location = "http://www.domain.com" will cause this problem in IE.

If you instead use location.href = "http://www.domain.com", it will only prompt the user once.

Hopefully this helps someone out!

like image 168
Kanuea Avatar answered Jan 12 '23 10:01

Kanuea