I need a function to return true if the given variable name is already defined by javascript engine or browser.
For example
isNative('window') //true;
isNative('Math') //true;
isNative('myVar') //false
isNative('navigator') //true
isNative('document') //true
Ok I found the solution.
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;
}
Additional code that can be added to the top to guard against edge condition of code running before document.body
is available:
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
}
...
}