Gri*_*Lab 36 javascript browser properties window-object
有没有办法在javascript中找出所有用户定义的窗口属性和变量(全局变量)?
我尝试了,console.log(window)
但列表是无止境的.
jun*_*ngy 77
您还可以将窗口与窗口的干净版本进行比较,而不是在运行时尝试快照以进行比较.我在控制台中运行它,但你可以把它变成一个函数.
// make sure it doesn't count my own properties
(function () {
var results, currentWindow,
// create an iframe and append to body to load a clean window object
iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
// get the current list of properties on window
currentWindow = Object.getOwnPropertyNames(window);
// filter the list against the properties that exist in the clean window
results = currentWindow.filter(function(prop) {
return !iframe.contentWindow.hasOwnProperty(prop);
});
// log an array of properties that are different
console.log(results);
document.body.removeChild(iframe);
}());
Run Code Online (Sandbox Code Playgroud)
你需要自己做这项工作.尽可能在第一时间阅读所有酒店.从那时起,您可以将属性列表与静态列表进行比较.
var globalProps = [ ];
function readGlobalProps() {
globalProps = Object.getOwnPropertyNames( window );
}
function findNewEntries() {
var currentPropList = Object.getOwnPropertyNames( window );
return currentPropList.filter( findDuplicate );
function findDuplicate( propName ) {
return globalProps.indexOf( propName ) === -1;
}
}
Run Code Online (Sandbox Code Playgroud)
所以现在,我们可以这样做
// on init
readGlobalProps(); // store current properties on global object
Run Code Online (Sandbox Code Playgroud)
然后
window.foobar = 42;
findNewEntries(); // returns an array of new properties, in this case ['foobar']
Run Code Online (Sandbox Code Playgroud)
当然,这里需要注意的是,您只能在脚本能够在最早的时间调用它时"冻结"全局属性列表.
这与@jungy的回答具有相同的精神,但我们可以分三行进行:
document.body.appendChild(document.createElement('div')).innerHTML='<iframe id="temoin" style="display:none"></iframe>';
for (a in window) if (!(a in window.frames[window.frames.length-1])) console.log(a, window[a])
document.body.removeChild($$('#temoin')[0].parentNode);
Run Code Online (Sandbox Code Playgroud)
首先,我们添加一个隐藏的iframe;然后我们根据iframe中的标准JavaScript API测试现有变量;然后我们删除iframe。
为了更方便地工作,按字母顺序对结果进行排序可能会很有用,但仍然可以使用3行版本:
document.body.appendChild(document.createElement('div')).innerHTML='<iframe id="temoin" style="display:none"></iframe>';
Object.keys(window).filter(a => !(a in window.frames[window.frames.length-1])).sort().forEach((a,i) => console.log(i, a, window[a]));
document.body.removeChild($$('#temoin')[0].parentNode);
Run Code Online (Sandbox Code Playgroud)
它可以打包成书签:
javascript:document.body.appendChild(document.createElement('div')).innerHTML='<iframe%20id="temoin"%20style="display:none"></iframe>';Object.keys(window).filter(a=>!(a%20in%20window.frames[window.frames.length-1])).sort().forEach((a,i)=>console.log(i,a,window[a]));document.body.removeChild(document.querySelectorAll('#temoin')[0].parentNode);throw 'done';
Run Code Online (Sandbox Code Playgroud)