tags:

views:

38

answers:

1

I would like to check if an object is an instanceof a certain built-in class. The problem is that my checking code might not be in the window where the object is defined, so x instanceof String would return false even though x is a String. What I need is something like x instanceof getWindowOf(x)['String']? But is it possible to define a function such as getWindowOf?

Or, we could solve this in another way if we were able to get all the windows of a JS application. top, and looping recursively through top.frames come close, but we would be missing pop-ups.

So what's a solution?

Note that I am just using String as an example. I really want to check classes like Element or any other classes defined in the browser.

+1  A: 

To avoid the cross-frame issues that you are having with the instanceof operator, and as you want to check a certain built-in object, I would recommend you to use the Object.prototype.toString method, it returns a string containing the internal [[Class]] property, e.g. assuming that str is a String and arr is an Array object both from other frame:

Object.prototype.toString.call(str); // returns "[object String]"
Object.prototype.toString.call(arr); // returns "[object Array]"
// while
str instanceof String; // is false
arr instanceof Array; // is false
// and 
typeof arr; // "object"

More info:

CMS
But then, you wouldn't be able to check hierarchies. Say a HTMLDivElement is an Element.
namin