Sau khi toying xung quanh với nhiều lựa chọn, tôi tin rằng đây là phương pháp chính xác nhất để phát hiện nếu một đối tượng là một cửa sổ trình duyệt chéo:
(function() {
"use strict";
var wStr;
wStr = Object.prototype.toString.call(window);
function isWindow(arg) {
var e,
str,
self,
hasSelf;
//Safari returns DOMWindow
//Chrome returns global
//Firefox, Opera & IE9 return Window
str = Object.prototype.toString.call(arg);
switch (wStr) {
case '[object DOMWindow]':
case '[object Window]':
case '[object global]':
return str === wStr;
}
///window objects always have a `self` property;
///however, `arg.self == arg` could be fooled by:
///var o = {};
///o.self = o;
if ('self' in arg) {
//`'self' in arg` is true if
//the property exists on the object _or_ the prototype
//`arg.hasOwnProperty('self')` is true only if
//the property exists on the object
hasSelf = arg.hasOwnProperty('self');
try {
if (hasSelf) {
self = arg.self;
}
delete arg.self;
if (hasSelf) {
arg.self = self;
}
} catch (e) {
//IE 7&8 throw an error when window.self is deleted
return true;
}
}
return false;
}
}());
tôi sẽ cần phải thực hiện một số chặt chẽ hơn đơn vị thử nghiệm, do đó, hãy cho tôi biết về bất kỳ sự mâu thuẫn nào phát sinh.
bạn có thể chỉ cần làm một thử nghiệm tương đương với 'window'? '(somevar === window)? 'yes': 'no'' –
Nhưng nếu đó là một cửa sổ iframe thì nó sẽ không hoạt động. – mck89
Tôi tò mò, tại sao bạn cần phải làm điều này? –