views:

51

answers:

5

Hi, do you know a good way to check if a variable is the window object in javascript? I tried with:

var variable=window;
Object.prototype.toString.call(variable);

In Firefox it returns "[object Window]" but in IE "[object Object]" so that's not the right way. Do you know an accurate way to check it?

+1  A: 
variable == window

Someone could still define a local variable called window. I'm not sure there's a way that's resilient to all such shenanigans. Someone could make an object that copied most of the window properties and functions, including toString.

Matthew Flaschen
+1  A: 
if(variable == window)

That of course only checks if the variable object is this window (i.e. the window of the document executing the javascript).

Alternatively, you could try something like this:

if(variable.document && variable.location)

And check for the existance of a few window fields and/or functions so you are pretty sure that it is a window...

inflagranti
+1  A: 

How about just:

isWindow = variable === window;

The triple-equals prevents type coercion that otherwise would make this much harder to do.

Andrew
Yes but i need a way to check every window not only the current one.
mck89
The type-strict check isn't necessary when comparing the same object.
Andy E
+4  A: 

Yes but i need a way to check every window not only the current one

There are a few ways you can do this. The simplest method is to check for one or two known properties on the window object. There's also the self property - for each window, you could check the self property is equal to the window object:

myvar.self == myvar;
window.self == window;
frameElement.contentWindow.self == frameElement.contentWindow;
Andy E
Perfect thanks!
mck89
A: 

Since window is a global variable and global variables are properties of the global object, window.window will equal window. So you could test:

if (mysteryVariable.window == mysteryVariable)
    ...

The problem is that this can be fooled if we have an object like this:

var q = {};
q.window = q;

If that's not likely, then you can use this code.

Casey Hope