列出网站使用的所有全局变量的方法是什么?任何浏览器javascript调试器都可以这样做吗?使用我的意思是READ,没有改变/添加。检测iframe,也会很好。
请注意: 我需要获取一个由网站“触及”的全局变量列表。并非所有这些或已添加的或已编辑的,都是在站点脚本中的任何位置使用的。
答案 0 :(得分:72)
在Chrome中,转到开发工具并打开控制台。 然后输入以下内容:
Object.keys( window );
这将为您提供一个包含所有全局变量的数组。
修改强>
在Google上搜索了一下之后,我找到了一种方法。您需要 firefox 和 jslinter 插件。
设置完成后,打开jslinter并转到选项 - >检查左栏上的所有内容,除了“容忍未使用的参数”。
然后在网页上运行jslinter并向下滚动结果。您将获得未使用变量的列表(全局,然后是每个函数的本地变量)。
现在在控制台中运行Object.keys(window);
并比较两者的结果以确定使用哪些。
答案 1 :(得分:7)
您可以尝试使用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.");
}
});
});
当然,属性描述符等与旧版浏览器不兼容。请注意,有一些全局变量/ window
属性可能无法以编程方式列出(如on*
处理程序),如果需要它们,则必须在数组中明确列出它们。请参阅相关问题List all properties of window object?和Cross Browser Valid JavaScript Names。
然而,我想运行一个代码覆盖率工具可以提供有关未声明的全局变量的信息,比如@stackErro建议,更有帮助。
答案 2 :(得分:6)
由于这个问题是Google搜索如何列出全局javascript变量的第一个问题,我将为此添加自己的答案。有时您需要列出全局变量,以查看您的代码是否没有泄漏到范围之外的变量(没有' 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]]);
}
})();
它将列出标准的全局变量,如窗口,文档,位置等。这些变量很少。因此,您可以轻松地在列表中找到泄露的变量。
答案 3 :(得分:4)
我所做的是。我找到了一个页面,其中包含尽可能少的JavaScript / Frameworks,并将所有键记录在数组中。 然后,迭代新页面上的所有键,并仅记录上一个站点中未列出的键。 您可以尝试一下,也可以使用我的代码段
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);
答案 4 :(得分:2)
将以下代码复制并粘贴到您的javascript控制台
中var keys = Object.getOwnPropertyNames( window ),
value;
for( var i = 0; i < keys.length; ++i ) {
value = window[ keys[ i ] ];
console.log( value );
}
对RightSaidFred(Javascript - dumping all global variables)
的所有信用我希望能帮到你
答案 5 :(得分:2)
列出我有时使用的全局变量的简单方法。 首先在执行任何脚本之前尽早放置此代码。
var WINDOW_PROPS = Object.keys(window);
然后,当您需要发现全局变量时,只需执行以下操作:
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"));
我在这里使用了一些ES6功能来缩短代码。它仍然不适合生产,但足以用于调试目的,并且应该适用于现代浏览器。
答案 6 :(得分:0)
这种单行代码可以使您更加接近,并且不需要在页面加载之前安装任何其他内容或运行代码:
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)
它基于以下三个原理过滤Object.keys(window):
window.foo = 'bar'
定义的全局变量具有外观特殊的属性描述符,我们可以利用它。请注意,如果脚本使用带有不同描述符的Object.defineProperty定义属性,我们将错过它们,但这在实践中很少见。答案 7 :(得分:0)
从Object.keys(window)中获取列表,删除浏览器默认生成的全局变量,只剩下在页面上声明的全局变量。注意:您声明的函数也算作全局变量。
const listGlobal = ()=> { //for debugging purposes
//put this function inside your html or javascript. Go to the html page.
//In chrome console type listGlobal(); to see list of global vars
//Array of global variables that exist in chrome browser by default
var stdChromeVars = ["parent","opener","top","length","frames","closed","location","self","window","document","name","customElements","history","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","status","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","onabort","onblur","oncancel","oncanplay","oncanplaythrough","onchange","onclick","onclose","oncontextmenu","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","onseeked","onseeking","onselect","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","ontransitionend","onafterprint","onbeforeprint","onbeforeunload","onhashchange","onlanguagechange","onmessage","onmessageerror","onoffline","ononline","onpagehide","onpageshow","onpopstate","onrejectionhandled","onstorage","onunhandledrejection","onunload","performance","stop","open","alert","confirm","prompt","print","queueMicrotask","requestAnimationFrame","cancelAnimationFrame","captureEvents","releaseEvents","requestIdleCallback","cancelIdleCallback","getComputedStyle","matchMedia","moveTo","moveBy","resizeTo","resizeBy","scroll","scrollTo","scrollBy","getSelection","find","webkitRequestAnimationFrame","webkitCancelAnimationFrame","fetch","btoa","atob","setTimeout","clearTimeout","setInterval","clearInterval","createImageBitmap","close","focus","blur","postMessage","onappinstalled","onbeforeinstallprompt","crypto","indexedDB","webkitStorageInfo","sessionStorage","localStorage","chrome","applicationCache","onpointerrawupdate","trustedTypes","speechSynthesis","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","openDatabase","caches","ondevicemotion","ondeviceorientation","ondeviceorientationabsolute"];
//load the current list of global variables
let thisdocVars = Object.keys(window);
//remove from the current list any variables that's in the browser default list
stdChromeVars.forEach(DelFunc);
function DelFunc(item) {
thisdocVars.forEach((e,i)=>{if(e==item){thisdocVars.splice(i, 1);}});
}
//separate variables into functions and variables
let thisdocfunc = [];
let thisdocvar = [];
thisdocVars.forEach((e)=>{if(typeof window[e]=="function"){thisdocfunc.push(e);}else{thisdocvar.push(e);}});
console.log("Global Functions:\n" + thisdocfunc);
console.log("Global Variables:\n" + thisdocvar);
//Ctrl+Shift+i to see console in chrome
}
答案 8 :(得分:-1)
您可以尝试使用JetBrains PhpStorm这就是我所做的,您可以免费试用任何系统30天。然后检查JSLint或JSHint或两者我都记不住了,然后所有未使用的变量都加下划线,用不同的颜色突出显示(根据主题)并在滚动条上可见,当你将鼠标悬停在它们上面时,它表示未使用的变量;
编辑: 我认为社区版现在免费。