How can I prevent window.onbeforeunload from being triggered by javascript: href links in IE?

Maxx picture Maxx · Oct 4, 2011 · Viewed 28.5k times · Source

I'm building a fail safe for my form that is going to warn users that if they leave the page their form data will be lost (similar to what gmail does).

window.onbeforeunload = function () {    
        if (formIsDirty) {
            return "You have unsaved data on this form. Don't leave!";
        }
}

The above function works great in firefox, but in IE it is triggered by any href link, even ones that are links to javascript and not other pages.

for example....

<a href='javascript:someFunction();'>click</a>

I'm wondering if there is any way to get around this, as I do not want the user thinking that they are leaving the page when they are simply clicking a button on it. I do not have the option of rewriting all the various links as they are built in and numerous.

Any ideas?

Answer

Dr.Molle picture Dr.Molle · Oct 4, 2011

You may remove and re-assign the onbeforeunload when hovering those links:

jQuery(
  function($)
  {
      //store onbeforeunload for later use
    $(window).data('beforeunload',window.onbeforeunload);  

      //remove||re-assign onbeforeunload on hover 
    $('a[href^="javascript:"]')
      .hover( 
             function(){window.onbeforeunload=null;},
             function(){window.onbeforeunload=$(window).data('beforeunload');}
            );

  }
);