Sergio
Sergio

Reputation: 1179

In-browser-javascript: under what circumstances does window.open return null/undefined?

The exception handling code of my web application sometimes reports back that window.open returns null or undefined. This is sporadic and I see it happening most of the time with Firefox 4.0.1 and 5.0 and, to a lesser extent, with Chrome.

When and why does that happen in correlation with a specific browser?

I heard somewhere that IE8 and IE9 can do that when working in protected mode. Is that true? And what about Firefox? Opera? Chrome? Safari?

Important notes:

  1. window.open is invoked directly inside an onclick event (it is not deferred as that would cause most browser's popup blocker to display an alert).
  2. window.open opens a blank window whose HTML content is then manipulated via javascript
  3. please do not reply telling me "why do you use window.open? why not instead do (anything else here)" as this would be off-topic.

Upvotes: 2

Views: 3178

Answers (1)

Sergio
Sergio

Reputation: 1179

I'll try to answer my own question with what I've been able to gather. I'll update it as soon as I discover more.

Firefox:

The popup blocker embedded in Firefox automatically blocks all asynchronous calls to window.open and the effect is that window.open returns null/undefined.

To avoid this, the window.open call must be synchronous and directly originating from an explicit user action like a mouse click.

If you need to modify the opened window based on data from an asynchronous event (e.g.: an XMLHttpRequest) you can synchronously open an empty window, cache the returned window object and than later update that.

This "hack" works with all browsers.

Upvotes: 6

Related Questions