javascript - window.open 返回 null 并在内联脚本中失败,但可以从控制台运行

标签 javascript window.open

我正在使用 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 仅当它被用户操作调用时才不会被阻止,例如在点击事件中,由 native 浏览器事件发出。 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

关于javascript - window.open 返回 null 并在内联脚本中失败,但可以从控制台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18401331/

相关文章:

php - 如何使用 jquery 调用 cakephp 操作?

javascript - 如何循环/处理 Javascript Key :Value pairs?

php - window.open向php传递参数并触发pdf创建和查看

javascript - document.write 在一个新的 open.document 中

javascript - 最内层元素上的调度事件不会导致向上层元素冒泡?

c# - 使用 <text> 标签的 MVC .Net 4 Razor 问题

Javascript 将部分字符串替换为变量

javascript - 关于innerHTML的几个问题

javascript - 有没有办法强制在选项卡中打开 "onclick"新窗口?

javascript - window.open 无法正常工作,解析 URL 被 chop