Search code examples
jqueryinternet-explorer-8popupparent-childonbeforeunload

How to set onbeforeunload status of window.opener from the child window?


I created the following code that works smoothly in Firefox and Chrome. In IE8 the window.opener.onbeforeunload = null line does not fire. Can anybody give me advise on how to get a similar result for IE8, i.e. deactivate all previous onbeforeunload settings of the parent window from a child window and then change (parent)window.location?

Thanks!

// this is just the activation of the site's onbeforeunload...
jQuery(document).ready(function(){
 var preventUnloadPrompt;
 jQuery('form').live('submit', function() { preventUnloadPrompt = true; });
 window.onbeforeunload = function() {
  var rval;
  if(preventUnloadPrompt) {
   return;
  } else {
   return 'Do you want to continue?';
  }
  return rval;
 }

//Now when clicking a button on the main site, a popup is opening 
//via popup = window.open{...}. In the popup there is another 
//button "Test" which should set the parent window's onbeforeunload 
//to zero and load another website in there. The function test() is 
//defined in the header, but here it is again to make reading easier:
//function test(){window.opener.onbeforeunload = null;
//window.opener.location="http://www.google.com";}

$("#button").click(function(){
 var content = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"><head><title>Popup</title><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js?v=1.4.4"></script><script type="text/javascript">function test(){window.opener.onbeforeunload = null; window.opener.location="http://www.google.com";}</script></head><body><div id="popup-message-stopbutton"><input type="button" value="Test" onclick="test()" /></div></body></html>';

 var popup = window.open('','', 'width="100",height="100"');
 popup.document.write(content);
 popup.document.close();
});

});


Solution

  • I see that this is an older post, but I just thought that I would share how I got around getting the onbeforeunload to unbind in the parent window from the child. Hopefully it will help someone.

    In the js for the parent window, write a function to unbind the event

    function unbindOBE(){
         $(window).unbind('beforeunload');
    }
    

    In the js for the child window, simply call the function before you reload or assign or what have you.

    window.opener.unbindOBE();
    

    With that said, if you are trying to change the location,

    window.opener.location="http://www.google.com";

    it would work much better if you used one of the assign or replace methods

    window.opener.location.assign("http://www.google.com");
    

    I haven't tried this in IE so YMMV