javascript 列出站点使用的所有 js 全局变量(并非全部定义!)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17276206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List all js global variables used by site (not all defined!)
提问by Flash Thunder
What is the way to list all global variables that have been used by the site? Can any browser javascript debugger do that? By used I mean READ, not changed/added. Detect iframe ones, would be nice too.
列出站点已使用的所有全局变量的方法是什么?任何浏览器 javascript 调试器都可以做到这一点吗?使用我的意思是阅读,而不是更改/添加。检测 iframe 的,也会很好。
PLEASE NOTE: I need to get a list of global variables "touched" by site. Not all of them or added ones or edited ones, the ones that were used anywhere in the site scripts.
请注意:我需要获取站点“触及”的全局变量列表。不是所有的,也不是添加的或编辑过的,在站点脚本中的任何地方都使用过的。
回答by stackErr
In Chrome, go to Dev tools and open the console. Then type in the following:
在 Chrome 中,转到开发工具并打开控制台。然后输入以下内容:
Object.keys( window );
This will give you an Array of all the global variables.
这将为您提供所有全局变量的数组。
EDIT
编辑
After searching on Google a bit, I found a way. You will need firefoxand the jslinteraddon.
在谷歌上搜索了一下之后,我找到了一种方法。您将需要firefox和jslinter插件。
Once setup, open jslinter and go to Options->check everythingon the left column except "tolerate unused parameters".
设置完成后,打开 jslinter 并转到选项->检查左列中除“容忍未使用的参数”之外的所有内容。
Then run jslinter on the webpage and scroll down in the results. You will have a list of unused variables(global and then local to each function).
然后在网页上运行 jslinter 并在结果中向下滚动。您将有一个未使用的变量列表(每个函数的全局变量和局部变量)。
Now run Object.keys(window);
in the console and compare the results from both to figure out which ones are used.
现在Object.keys(window);
在控制台中运行并比较两者的结果以找出使用了哪些。
回答by Viktor Vesely
What i did was. I found a page with as little JavaScript / Frameworks as possible, logged all their keys in array. Then iterated all the keys on the new page and logged only those which were not listed in the previous site. You can try it or use my code snippet
我所做的是。我找到了一个尽可能少的 JavaScript / 框架的页面,将它们的所有键都记录在数组中。然后迭代新页面上的所有键,只记录上一个站点中未列出的键。您可以尝试或使用我的代码片段
var ks = ["postMessage","blur","focus","close","frames","self","window","parent","opener","top","length","closed","location","document","origin","name","history","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","status","frameElement","navigator","customElements","external","screen","innerWidth","innerHeight","scrollX","pageXOffset","scrollY","pageYOffset","screenX","screenY","outerWidth","outerHeight","devicePixelRatio","clientInformation","screenLeft","screenTop","defaultStatus","defaultstatus","styleMedia","onanimationend","onanimationiteration","onanimationstart","onsearch","ontransitionend","onwebkitanimationend","onwebkitanimationiteration","onwebkitanimationstart","onwebkittransitionend","isSecureContext","onabort","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","oncuechange","ondblclick","ondrag","ondragend","ondragenter","ondragleave","ondragover","ondragstart","ondrop","ondurationchange","onemptied","onended","onerror","onfocus","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","onseeked","onseeking","onselect","onstalled","onsubmit","onsuspend","ontimeupdate","ontoggle","onvolumechange","onwaiting","onwheel","onauxclick","ongotpointercapture","onlostpointercapture","onpointerdown","onpointermove","onpointerup","onpointercancel","onpointerover","onpointerout","onpointerenter","onpointerleave","onafterprint","onbeforeprint","onbeforeunload","onhashchange","onlanguagechange","onmessage","onmessageerror","onoffline","ononline","onpagehide","onpageshow","onpopstate","onrejectionhandled","onstorage","onunhandledrejection","onunload","performance","stop","open","alert","confirm","prompt","print","requestAnimationFrame","cancelAnimationFrame","requestIdleCallback","cancelIdleCallback","captureEvents","releaseEvents","getComputedStyle","matchMedia","moveTo","moveBy","resizeTo","resizeBy","getSelection","find","webkitRequestAnimationFrame","webkitCancelAnimationFrame","fetch","btoa","atob","setTimeout","clearTimeout","setInterval","clearInterval","createImageBitmap","scroll","scrollTo","scrollBy","onappinstalled","onbeforeinstallprompt","crypto","ondevicemotion","ondeviceorientation","ondeviceorientationabsolute","indexedDB","webkitStorageInfo","sessionStorage","localStorage","chrome","visualViewport","speechSynthesis","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","addEventListener", "removeEventListener", "openDatabase", "dispatchEvent"]
var newKs = []
for (key in window) {
if(ks.indexOf(key) == -1 && key !== "ks" && key !=="newKs") {
newKs.push(key);
}
}
console.log(newKs);
回答by Bergi
You could try to use getters for that, which you create for all existing global variables. Run this before the page is started:
您可以尝试为此使用 getter,您可以为所有现有的全局变量创建它。在页面启动之前运行:
Object.keys(window) // or
Object.getOwnPropertyNames(window).concat(
Object.getOwnPropertyNames(Object.getPrototypeOf(window))
) // or whatever
.forEach(function(name) {
var d = Object.getOwnPropertyDescriptor(window, name),
def = Object.defineProperty,
log = console.log.bind(console);
if (d && !d.configurable)
return log("cannot detect accessing of "+name);
def(window, name, {
configurable: true,
get: function() {
log("window."+name+" was used by this page!");
if (d) {
def(window, name, d);
return d.get ? d.get() : d.value;
} else { // it was not an own property
delete window[name];
return window[name];
}
},
set: function(x) {
log("Ugh, they're overwriting window."+name+"! Something's gonna crash.");
}
});
});
Of course property descriptors etc. are not compatible with older browsers. And notice that there are some global variables / window
properties that might not be programmatically listable (like on*
handlers), if you need them you will have to explicitly list them in the array. See the related questions List all properties of window object?and Cross Browser Valid JavaScript Namesfor that.
当然,属性描述符等与旧浏览器不兼容。请注意,有些全局变量/window
属性可能无法以编程方式列出(如on*
处理程序),如果您需要它们,则必须在数组中明确列出它们。查看相关问题列出窗口对象的所有属性?和跨浏览器有效 JavaScript 名称。
Yet I guess running a code coverage tool that whinges about undeclared global variables, like @stackErro suggested, is more helpful.
然而,我想运行一个代码覆盖工具来抱怨未声明的全局变量,就像@stackErro 建议的那样,更有帮助。
回答by Tomas M
Since this question is the first in google when searching for a way how to list global javascript variables, I will add my own answer for that. Sometimes you need to list global variables to see if your code does not have a variable leaked outside the scope (defined without 'var'). For that, use this in the debug console:
由于在搜索如何列出全局 javascript 变量的方法时,这个问题是 google 中的第一个问题,因此我将为此添加我自己的答案。有时您需要列出全局变量以查看您的代码是否没有泄漏到范围之外的变量(未定义 'var')。为此,请在调试控制台中使用它:
(function ()
{
var keys=Object.keys( window );
for (var i in keys)
{
if (typeof window[keys[i]] != 'function')
console.log(keys[i], window[keys[i]]);
}
})();
It will list the standard global variables, like window, document, location, etc. Those are just few. So you can find your leaked vars in the list easily.
它将列出标准的全局变量,如窗口、文档、位置等。这些只是少数。所以你可以很容易地在列表中找到你泄露的变量。
回答by jd20
This one-liner will get you pretty close, and does not require installing anything additional, or running code before the page loads:
这种单行代码将使您非常接近,并且不需要在页面加载之前安装任何其他内容或运行代码:
Object.keys(window).filter(x => typeof(window[x]) !== 'function' &&
Object.entries(
Object.getOwnPropertyDescriptor(window, x)).filter(e =>
['value', 'writable', 'enumerable', 'configurable'].includes(e[0]) && e[1]
).length === 4)
It filters Object.keys(window) based on three principles:
它基于三个原则过滤 Object.keys(window):
- Things that are null or undefined are usually not interesting to look at.
- Most scripts will define a bunch of event handlers (i.e. functions) but they are also usually not interesting to dump out.
- Properties on window that are set by the browser itself, are usually defined in a special way, and their property descriptors reflect that. Globals defined with the assignment operator (i.e.
window.foo = 'bar'
) have a specific-looking property descriptor, and we can leverage that. Note, if the script defines properties using Object.defineProperty with a different descriptor, we'll miss them, but this is very rare in practice.
- null 或 undefined 的东西通常看起来并不有趣。
- 大多数脚本会定义一堆事件处理程序(即函数),但它们通常也没有兴趣转储出来。
- 由浏览器本身设置的窗口属性通常以特殊方式定义,并且它们的属性描述符反映了这一点。使用赋值运算符(即
window.foo = 'bar'
)定义的全局变量具有特定外观的属性描述符,我们可以利用它。请注意,如果脚本使用带有不同描述符的 Object.defineProperty 定义属性,我们会错过它们,但这在实践中非常罕见。
回答by UNX
copy and paste the following code into your javascript console
将以下代码复制并粘贴到您的 javascript 控制台中
var keys = Object.getOwnPropertyNames( window ),
value;
for( var i = 0; i < keys.length; ++i ) {
value = window[ keys[ i ] ];
console.log( value );
}
all credits to RightSaidFred (Javascript - dumping all global variables)
全部归功于 RightSaidFred(Javascript - 转储所有全局变量)
i hope that helped you
我希望对你有帮助
回答by Евгений Савичев
Easy way to list your globals I use sometimes. First put this code as early as possible, before any of your scripts executed.
列出我有时使用的全局变量的简单方法。在执行任何脚本之前,请尽可能早地放置此代码。
var WINDOW_PROPS = Object.keys(window);
Then at the moment when you need to discover your globals just do something like this:
然后,当您需要发现全局变量时,只需执行以下操作:
var GLOBALS = Object.keys(window)
// filter the props which your code did not declare
.filter(prop => WINDOW_PROPS.indexOf(prop) < 0)
// prettify output a bit :) It's up to you...
.map(prop => `${typeof window[prop]} ${prop} ${window[prop]}`)
// sort by types and names to find easier what you need
.sort();
console.log(GLOBALS.join("\n"));
I've used some ES6 features here to shorten the code. It's still not good for production, but good enough for debug purposes and should work in modern browsers.
我在这里使用了一些 ES6 特性来缩短代码。它仍然不适合生产,但足以用于调试目的并且应该在现代浏览器中工作。
回答by Jacek Pietal
You can try using JetBrains PhpStorm that's what I do, you can get a trial of 30 days for free for any system. Then you check on JSLint or JSHint or both I cant remember and then all your unused variables are underlined, highlighted with different color (according to theme) and visible on the scrollbar and when you hover over them it says unused variable;
您可以尝试使用 JetBrains PhpStorm,我就是这样做的,您可以免费试用 30 天,适用于任何系统。然后你检查 JSLint 或 JSHint 或我不记得的两者,然后你所有未使用的变量都带有下划线,用不同的颜色突出显示(根据主题)并且在滚动条上可见,当你将鼠标悬停在它们上面时,它会显示未使用的变量;
EDIT: I think community version is free now.
编辑:我认为社区版现在是免费的。