javascript有没有办法检测所有分配的变量?例如,如果一个 js 文件创建了一堆变量(全局范围),后续文件是否可以在不知道它们的名称和可能存在的情况下获取所有变量?
提前致谢:)
编辑,问题第 2 部分:
如何获取这些变量的值?这是我尝试过的:
这就是我根据评论建议得到的结果:
for (var name in this) {
variables[name] = name;
variables[name]=this[name]
}
Flanagan 的“JavaScript - 权威指南”在第 653 页给出了以下内容:
var variables = ""
for (var name in this)
variables += name + "\n";
对于 Firefox,您可以看到 DOM 选项卡——很简单,但不能回答您的问题。
Kinopiko 的答案中提供的for in
循环可以工作,但在 IE 中不行。下面链接的文章中有更多解释。对于 IE,请使用
RuntimeObject
。
if(this.RuntimeObject){
void function() {
var ro = RuntimeObject(),
results = [],
prop;
for(prop in ro) {
results.push(prop);
}
alert("leaked:\n" + results.join("\n"));
}();
}
另请参阅:
this
变量。这是一个对象或数组,你可以简单地输入:
for(i in this) { //do something }
不幸的是,它将返回
this
对象下的 一切
。
var variables = ""
for (var name in this)
variables += name + "\n";
console.log(variables)
/*
This could work too... but it's such a big unecessary code for something you could do in one line
var split = variables.split("\n");
for (var i in split)
console.log(split[i])
*/
//Way 1st
const variables= { ...this };
// or (I don't know what's the difference ;) )
// Don't forget const variables= {};
Object.assign(variables, this);
// Yes. It's very easy. You just "copy" entries from this to variables. I want to note that you are not copying a link to this, namely ENTRY.
// Way 2nd. If u need to do smth. with entries.
const variables= [];
for (const name of Object.keys(this)) {
/*
Doing smth........
*/
variables[name] = this[name];
}
最佳方法: 这会删除大多数不需要的额外浏览器变量,并显示每个变量的值
const browserVariables = ['value', 'window', 'self', 'document', 'name', 'location', 'customElements', 'history', 'locationbar', 'menubar', 'personalbar', 'scrollbars', 'statusbar', 'toolbar', 'status', 'closed', 'frames', 'length', 'top', 'opener', 'parent', 'frameElement', 'navigator', 'origin', 'external', 'screen', 'innerWidth', 'innerHeight', 'scrollX', 'pageXOffset', 'scrollY', 'pageYOffset', 'visualViewport', 'screenX', 'screenY', 'outerWidth', 'outerHeight', 'devicePixelRatio', 'clientInformation', 'screenLeft', 'screenTop', 'defaultStatus', 'defaultstatus', 'styleMedia', 'onsearch', 'isSecureContext', 'performance', 'onappinstalled', 'onbeforeinstallprompt', 'crypto', 'indexedDB', 'webkitStorageInfo', 'sessionStorage', 'localStorage', 'onbeforexrselect', 'onabort', 'onblur', 'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncuechange', 'ondblclick', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'onformdata', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onpause', 'onplay', 'onplaying', 'onprogress', 'onratechange', 'onreset', 'onresize', 'onscroll', 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 'onslotchange', 'onstalled', 'onsubmit', 'onsuspend', 'ontimeupdate', 'ontoggle', 'onvolumechange', 'onwaiting', 'onwebkitanimationend', 'onwebkitanimationiteration', 'onwebkitanimationstart', 'onwebkittransitionend', 'onwheel', 'onauxclick', 'ongotpointercapture', 'onlostpointercapture', 'onpointerdown', 'onpointermove', 'onpointerup', 'onpointercancel', 'onpointerover', 'onpointerout', 'onpointerenter', 'onpointerleave', 'onselectstart', 'onselectionchange', 'onanimationend', 'onanimationiteration', 'onanimationstart', 'ontransitionrun', 'ontransitionstart', 'ontransitionend', 'ontransitioncancel', 'onafterprint', 'onbeforeprint', 'onbeforeunload', 'onhashchange', 'onlanguagechange', 'onmessage', 'onmessageerror', 'onoffline', 'ononline', 'onpagehide', 'onpageshow', 'onpopstate', 'onrejectionhandled', 'onstorage', 'onunhandledrejection', 'onunload', 'alert', 'atob', 'blur', 'btoa', 'cancelAnimationFrame', 'cancelIdleCallback', 'captureEvents', 'clearInterval', 'clearTimeout', 'close', 'confirm', 'createImageBitmap', 'fetch', 'find', 'focus', 'getComputedStyle', 'getSelection', 'matchMedia', 'moveBy', 'moveTo', 'open', 'postMessage', 'print', 'prompt', 'queueMicrotask', 'releaseEvents', 'reportError', 'requestAnimationFrame', 'requestIdleCallback', 'resizeBy', 'resizeTo', 'scroll', 'scrollBy', 'scrollTo', 'setInterval', 'setTimeout', 'stop', 'structuredClone', 'webkitCancelAnimationFrame', 'webkitRequestAnimationFrame', 'originAgentCluster', 'trustedTypes', 'navigation', 'speechSynthesis', 'onpointerrawupdate', 'crossOriginIsolated', 'scheduler', 'openDatabase', 'webkitRequestFileSystem', 'webkitResolveLocalFileSystemURL', 'chrome', 'caches', 'cookieStore', 'ondevicemotion', 'ondeviceorientation', 'ondeviceorientationabsolute', 'onbeforematch', 'getDigitalGoodsService', 'getScreenDetails', 'queryLocalFonts', 'showDirectoryPicker', 'showOpenFilePicker', 'showSaveFilePicker', 'variables', 'TEMPORARY', 'PERSISTENT', 'addEventListener', 'dispatchEvent', 'removeEventListener'];
var variables = '';
for (var name in this) {
if (!browserVariables.includes(name)) {
var value = eval(name);
if (value != null && value != undefined && typeof value != 'function') variables += 'var '+name+' = '+value+'\n';
}
}
console.log(variables);
[Object object]
。您可能想使用按钮异步或调用该函数,因为它在处理时停止。由于我没有添加任何内容来判断它是对象还是数组,所以有些
{}
要么是数组,要么是函数。也许有人可以重构我的脚本。如果您希望它打印成
<div>
,那么您需要将空格
更改为
,将换行符
\n
更改为
</br>
。请注意,它不包括
window、document、self、frames、top、parent、jQuery 和 $。
<textarea id="all-variables" readonly></textarea>
<script type="text/javascript">
(function() {
function stringCheck(string) {
return {
window: true,
document: true,
self: true,
frames: true,
top: true,
parent: true,
jQuery: true,
$: true
}[string] || false
}
function printObject(o) {
var output = '';
for (var p in o) {
output += ' '+ p + ': ' + o[p] + '\n';
}
return output;
}
const allVariables = document.getElementById('all-variables');
for (var variable in this) {
if (
(
(typeof this[variable] === 'object') || (typeof this[variable] === 'function')
) &&
(this[variable] != (undefined || null)) &&
(!stringCheck(variable))
) {
allVariables.innerHTML += variable +': {\n';
for (var secondVariable in this[variable]) {
if (
(
(typeof this[variable][secondVariable] === 'object') || (typeof this[variable][secondVariable] === 'function')
) &&
(this[variable][secondVariable] != (undefined || null))
) {
allVariables.innerHTML += ' '+ secondVariable +': {\n';
for (var thirdVariable in this[variable][secondVariable]) {
if (
(
(typeof this[variable][secondVariable][thirdVariable] === 'object') || (typeof this[variable][secondVariable][thirdVariable] === 'function')
) &&
(this[variable][secondVariable][thirdVariable] != (undefined || null))
) {
if (this[variable][secondVariable][thirdVariable][0] != undefined) {
allVariables.innerHTML += ' '+ thirdVariable +': {\n';
for (var i = 0; i < this[variable][secondVariable][thirdVariable].length; i++) {
allVariables.innerHTML += printObject(this[variable][secondVariable][thirdVariable][i]);
}
allVariables.innerHTML += ' }\n';
}
} else {
allVariables.innerHTML += ' '+ thirdVariable +': \''+ this[variable][secondVariable][thirdVariable] +'\'\n';
}
}
allVariables.innerHTML += ' }\n';
} else {
allVariables.innerHTML += ' '+ secondVariable +': \''+ this[variable][secondVariable] +'\'\n';
}
}
allVariables.innerHTML += '}\n';
} else {
allVariables.innerHTML += variable +
(
typeof this[variable] === 'string' ? ': \''+ this[variable].toString() +'\'' : ''
) +
'\n';
}
}
})();
</script>