列出站点使用的所有js全局变量(并非全部定义!)

时间:2020-12-28 16:49:16

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调试器都可以这样做吗?使用我的意思是READ,没有改变/添加。检测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.

请注意:我需要获取网站“触及”的全局变量列表。并非所有这些或已添加的或已编辑的,在站点脚本中的任何位置使用的那些。

7 个解决方案

#1


65  

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 firefox and the jslinter addon.

在Google上搜索了一下之后,我找到了一种方法。你需要firefox和jslinter插件。

Once setup, open jslinter and go to Options->check everything on the left column except "tolerate unused parameters".

设置完成后,打开jslinter并转到Options->检查左栏中的所有内容,除了“容忍未使用的参数”。

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(窗口);在控制台中,比较两者的结果,找出使用的结果。

#2


7  

You could try to use getters for that, which you create for all existing global variables. Run this before the page is started:

您可以尝试使用getters,为所有现有的全局变量创建。在页面启动之前运行此命令:

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 Names for that.

当然,属性描述符等与旧版浏览器不兼容。请注意,有一些全局变量/窗口属性可能无法以编程方式列出(如*处理程序),如果需要它们,则必须在数组中明确列出它们。查看相关问题列出窗口对象的所有属性?和跨浏览器有效的JavaScript名称。

Yet I guess running a code coverage tool that whinges about undeclared global variables, like @stackErro suggested, is more helpful.

然而,我想运行一个代码覆盖工具可以解决未申报的全局变量,比如@stackErro建议,更有帮助。

#3


6  

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变量的第一个问题,我将为此添加自己的答案。有时您需要列出全局变量,以查看您的代码是否没有泄漏到范围之外的变量(没有'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.

它将列出标准的全局变量,如窗口,文档,位置等。这些变量很少。因此,您可以轻松地在列表中找到泄露的变量。

#4


1  

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

我希望能帮助你

#5


1  

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功能来缩短代码。它仍然不适合生产,但足以用于调试目的,应该适用于现代浏览器。

#6


0  

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.

编辑:我认为社区版现在免费。

#7


0  

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 / 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);

#1


65  

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 firefox and the jslinter addon.

在Google上搜索了一下之后,我找到了一种方法。你需要firefox和jslinter插件。

Once setup, open jslinter and go to Options->check everything on the left column except "tolerate unused parameters".

设置完成后,打开jslinter并转到Options->检查左栏中的所有内容,除了“容忍未使用的参数”。

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(窗口);在控制台中,比较两者的结果,找出使用的结果。

#2


7  

You could try to use getters for that, which you create for all existing global variables. Run this before the page is started:

您可以尝试使用getters,为所有现有的全局变量创建。在页面启动之前运行此命令:

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 Names for that.

当然,属性描述符等与旧版浏览器不兼容。请注意,有一些全局变量/窗口属性可能无法以编程方式列出(如*处理程序),如果需要它们,则必须在数组中明确列出它们。查看相关问题列出窗口对象的所有属性?和跨浏览器有效的JavaScript名称。

Yet I guess running a code coverage tool that whinges about undeclared global variables, like @stackErro suggested, is more helpful.

然而,我想运行一个代码覆盖工具可以解决未申报的全局变量,比如@stackErro建议,更有帮助。

#3


6  

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变量的第一个问题,我将为此添加自己的答案。有时您需要列出全局变量,以查看您的代码是否没有泄漏到范围之外的变量(没有'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.

它将列出标准的全局变量,如窗口,文档,位置等。这些变量很少。因此,您可以轻松地在列表中找到泄露的变量。

#4


1  

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

我希望能帮助你

#5


1  

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功能来缩短代码。它仍然不适合生产,但足以用于调试目的,应该适用于现代浏览器。

#6


0  

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.

编辑:我认为社区版现在免费。

#7


0  

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 / 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);