JS无法检测到childWindow已关闭

时间:2015-03-11 02:48:43

标签: javascript jquery

我希望在子窗口关闭时运行一个函数,但它无法检查到window.closed

这是我的代码:

<button onclick='openChild(); ></button>

 <script language="JavaScript" type="text/javascript">

            function openChild(){                   
                var child_window = window.open('http://www.website.com','win1','toolbar=0,status=1,location=1,scrollbars=1,resizable=1,width=950,height=600');

                if(<?php echo $active?> ==0 ){
            setTimeout(function(child_window ){

                    child_window.close();
               }, 1000);
         }
  child_window.onunload =checkChild; 

  var check_token = setInterval(checkChild, 500);
    }       

 function checkChild() {
if (child_window && child_window.closed) {
    alert("Closed!");   
clearInterval(check_token);     
$.get("check.php", function(data) {});
location.reload();

}
   }

1 个答案:

答案 0 :(得分:1)

checkChild()函数中,变量childWindow不存在,但由于您使用checkChild()作为事件处理程序,因此可以将childWindow替换为this个关键字

function openChild(){                 
    var child_window = window.open('http://www.website.com','win1','toolbar=0,status=1,location=1,scrollbars=1,resizable=1,width=950,height=600');

    if(<?php echo $active?> ==0 ){
      child_window.close();
    }
    child_window.onunload = function() {
        // this functions fires when closed
        alert('closed');
        $.get("check.php", function(data) {});
        location.reload();
    };
}