我正在使用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
仅在用户操作(例如在本机浏览器事件发出的click事件中)调用时才被阻止。同样,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
在创建新窗口失败时返回的引用。