Pregunta

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>

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>.

¿Fue útil?

Solución

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>

Watch the Fiddle. I also tried it with the keypress event, but no luck.

window.open returns a valid reference to the new (or an existing named) window, or null when it failed to create a new window.

Otros consejos

Try the next command after window.open with timeout, for example:

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 );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top