我正在使用 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/