我正在使用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>
之前。
答案 0 :(得分:19)
它被浏览器阻止。 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
无法创建新窗口时的引用。
答案 1 :(得分:-4)
在带有超时的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 );