window.open在内联脚本中返回null并失败,但可以在控制台中工作
window.open returns null and fails in inline script but works from console
我使用的是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
被用户操作调用时,例如在本机浏览器事件发出的单击事件中,它才不会被阻止。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
。
在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 );
相关文章:
- 控制台返回var不是't定义,但它是
- 当json解析空响应时,Whatwg-Fetch失败,我该如何防止它
- 有没有一种方法可以在控制台关闭的情况下让console.log()在IE中记录消息
- JsFiddle在分叉后描述失败
- 如何使用Protractor从Chrome控制台获取所有日志
- 为什么不'当单元测试出现解析错误时,我的因果报应测试会失败
- 为什么我能够从javascript控制台发送跨域ajax请求
- 当一些承诺失败时,如何继续使用$q.all()
- 失败:等待Protractor与页面同步时出错:“”;在窗口上找不到角度”;
- 在Jquery中单击传播失败
- 当浏览器控制台未打开时,为什么要求会导致Internet Explorer 9超时
- 如何阻止 jQuery.ajax() 将失败记录到控制台
- JS失败,除非控制台打开
- 来自跨域的图像在HTML中显示良好,但ajax从浏览器控制台调用相同的图像失败
- 放肆的控制台运行程序无声失败
- 传单.addlayer()在功能上失败,在控制台工作
- 在AngularJS SPA中Google Chrome控制台的奇怪请求失败
- 当Mocha Test失败时,它将一个对象记录到控制台
- 如何使用QUnitJS将断言失败消息发送到控制台
- 当我尝试使用ajax时,chrome的控制台显示“资源加载失败”