开发者

How can I get the window in which an object was defined?

开发者 https://www.devze.com 2022-12-21 01:04 出处:网络
I would like to check if an object is an instanceof a certain bui开发者_运维知识库lt-in class. The problem is that my checking code might not be in the window where the object is defined, so x instanc

I would like to check if an object is an instanceof a certain bui开发者_运维知识库lt-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.


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:

  • instanceof considered harmful
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号