如何从子窗口设置window.opener的onbeforeunload状态?

时间:2012-10-31 08:12:26

标签: jquery internet-explorer-8 popup parent-child onbeforeunload

我创建了以下代码,可以在Firefox和Chrome中顺利运行。在IE8中,window.opener.onbeforeunload = null行不会触发。任何人都可以告诉我如何获得IE8的类似结果,即从子窗口中取消激活父窗口的所有先前onbeforeunload设置,然后更改(父)window.location?

谢谢!

// 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();
});

});

2 个答案:

答案 0 :(得分:0)

尝试使用jQuery访问opener并取消绑定事件,如下所示:

$(window.opener).unbind('onbeforeunload');

答案 1 :(得分:0)

我看到这是一篇较老的帖子,但我只想到我会分享如何让onbeforeunload从孩子的父窗口取消绑定。希望它会帮助别人。

在父窗口的js中,编写一个取消绑定事件的函数

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

在子窗口的js中,只需在重新加载或分配之前调用该函数或者你有什么。

window.opener.unbindOBE();

话虽如此,如果你想改变位置,

  

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

如果你使用了一个赋值或替换方法

,它会更好
window.opener.location.assign("http://www.google.com");

我没有在IE中尝试过这样的YMMV