如果给定的变量名称已由 javascript 引擎或浏览器定义,我需要一个函数返回 true。
例如
isNative('window') //true;
isNative('Math') //true;
isNative('myVar') //false
isNative('navigator') //true
isNative('document') //true
最佳答案
好的,我找到了解决方案。
function isNative(variableName) {
if (window['__emptyIframeRef__'] === undefined) {
window['__emptyIframeRef__'] = document.createElement('iframe');
window['__emptyIframeRef__'].setAttribute('style', 'display:none');
document.getElementsByTagName('body')[0].appendChild(window['__emptyIframeRef__']);
}
return window['__emptyIframeRef__'].contentWindow[variableName] !== undefined;
}
可以添加到顶部的其他代码,以防止在 document.body
可用之前运行的代码的边缘条件:
function isNative(variableName) {
if(o===null||o===undefined)return true
if(!document.body){
if(o instanceof String) o = window[o]
if(o===undefined) return false
if(o.constructor.toString().indexOf('[native code]')>-1) return true
return false
}
...
}
关于javascript - 如何在 JavaScript 中检测 native 浏览器/引擎对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20313848/