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

Fla*_*der 54 javascript

列出网站使用的所有全局变量的方法是什么?任何浏览器javascript调试器都可以这样做吗?使用我的意思是READ,没有改变/添加.检测iframe,也会很好.

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

sta*_*Err 76

在Chrome中,转到开发工具并打开控制台.然后输入以下内容:

Object.keys( window );
Run Code Online (Sandbox Code Playgroud)

这将为您提供所有全局变量的数组.

编辑

在Google上搜索了一下后,我找到了一种方法.你需要firefoxjslinter插件.

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

然后在网页上运行jslinter并向下滚动结果.您将获得一个未使用的变量列表(全局,然后是每个函数的本地变量).

现在Object.keys(window);在控制台中运行并比较两者的结果以确定使用哪些.

  • 这不是我的问题的答案.这列出了所有全局变量,我只想列出网站触及的一个变量. (2认同)
  • @DanDascalescu,但他想要使用/读取的变量,object.keys(window) 将列出未使用/未读的变量。 (2认同)

jd2*_*d20 15

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)
Run Code Online (Sandbox Code Playgroud)

It filters Object.keys(window) based on three principles:

  1. Things that are null or undefined are usually not interesting to look at.
  2. Most scripts will define a bunch of event handlers (i.e. functions) but they are also usually not interesting to dump out.
  3. 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.


Vik*_*elý 8

我所做的是。我找到了一个页面,其中包含尽可能少的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);
Run Code Online (Sandbox Code Playgroud)


Ber*_*rgi 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.");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

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

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


Tom*_*s M 5

由于这个问题是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]]);
   }
})();
Run Code Online (Sandbox Code Playgroud)

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