window.open在内联脚本中返回null并失败,但可以在控制台中工作

window.open returns null and fails in inline script but works from console

本文关键字:失败 控制台 工作 但可以 返回 open 脚本 window null      更新时间:2023-09-26

我使用的是Smarty模板系统。它的一个特性是可以输出为每个页面生成调试信息的脚本。在这里你可以看到一个生成代码的例子:

<script type="text/javascript">
//<![CDATA[
setTimeout(function() {  //Attempt to fix the issue with timeout
    var _smarty_console = window.open("about:blank","md5hash","width=680,height=600,resizable,scrollbars=yes");
    console.log(_smarty_console);  //Trying to log it
    if(_smarty_console!=null) {
      _smarty_console.document.write("<!DOCTY... lots of HTML ...<'/html>'n");
      _smarty_console.document.close();
    }
}, 5000);
//]]> 
</script>

问题是,window.open函数总是返回null。我试着用setTimeout来延迟,但没有任何改变。当我复制代码并在Firebug控制台中运行时,它可以正常工作。页面上并没有其他脚本。该页面使用严格的XHTML。脚本就在</body>之前。

它被浏览器阻止。当window.open被用户操作调用时,例如在本机浏览器事件发出的单击事件中,它才不会被阻止。javaScript发出的事件也被阻止,就像延迟的setTimeout回调一样。

<a id="link" href="http://stackoverflow.com">StackOverflow</a>
<script type="text/javascript">
// Example (with jQuery for simplicity)
$("a#link").click(function (e) {
  e.preventDefault();
  var url = this.href;
  // this will not be blocked
  var w0 = window.open(url);
  console.log("w0: " + !!w0); // w0: true
  window.setTimeout(function () {
    // this will be blocked
    var w1 = window.open(url);
    console.log("w1: " + !!w1); // w1: false
  }, 5000);
});
</script>

小心Fiddle。我也在keypress事件中尝试过,但没有成功。

window.open返回对新窗口(或现有命名窗口)的有效引用,或在创建新窗口失败时返回null

在window.open之后尝试下一个命令并超时,例如:

var myWindow = window.open('foo','_blank','menubar=no, scrollbars=yes, top=10, width=800,height=600');
setTimeout( myWindow.onload=function(){this.document.body.innerHTML+='bar';}, 2000 );