问题描述
我正在使用Smarty模板系统。其功能之一是输出脚本的可能性,该脚本为每个页面生成调试信息。在这里您可以看到生成代码的示例:
I'm using Smarty template system. One of its features is posibility to output script that generates debug information for every page. Here you can see an example of generated code:
<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>
之前。
The problem is, that the window.open
functions always returns null
. I tried to delay it with setTimeout
but nothing changed. When I copy the code and run it in Firebug console, it works properly. There are no other scripts on page. The page uses strict XHTML. The script is right before </body>
.
推荐答案
它被浏览器阻止。 window.open
只有在用户操作调用时才会被阻止,例如在本机浏览器事件发出的单击事件中。此外,javaScript发出的事件也被阻止,就像延迟的setTimeout回调一样。
It is blocked by the browser. window.open
is only not being blocked, when it is invoked by user action, for example in a click event, emitted by a native browser event. Also javaScript emitted events are being blocked, just like delayed setTimeout callbacks.
<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>
观看。我还尝试使用 keypress
事件,但没有运气。
Watch the Fiddle. I also tried it with the keypress
event, but no luck.
window.open
返回对新(或现有命名)窗口的有效引用,或 null
,当它无法创建新窗口时。
window.open
returns a valid reference to the new (or an existing named) window, or null
when it failed to create a new window.
这篇关于window.open返回null并在内联脚本中失败,但在控制台中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!