【问题标题】:window.open returns null and fails in inline script but works from consolewindow.open 返回 null 并在内联脚本中失败,但可以从控制台工作
【发布时间】:2013-08-23 11:06: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。脚本就在&lt;/body&gt;之前。

【问题讨论】:

  • 这可能是一个愚蠢的问题,但你真的能看到弹出窗口吗?如果不能,请关闭浏览器中的弹出窗口拦截器...

标签: javascript window.open


【解决方案1】:

它被浏览器阻止了。 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

【讨论】:

  • 我认为这与浏览器有关。但是由于没有“弹出窗口被阻止”。消息出现,我很困惑。你能给我一个建议如何让它工作吗?我当然希望它在不更改浏览器设置的情况下工作。
  • 没办法。仅通过点击事件,就像我帖子中的示例(更新)
  • 甚至没有一个按键事件起作用 (CTRL+j)。在这种情况下,我将不得不为我的页面添加一个例外。
【解决方案2】:

在 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 );

【讨论】:

  • 这有什么帮助?它与问题有什么关系?你能解释更多吗?
  • 与问题相关的这段代码是什么意思?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 2022-09-29
  • 2015-04-09
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
相关资源
最近更新 更多