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

Javascript 列出站点使用的所有js全局变量(未全部定义!),javascript,Javascript,列出站点使用过的所有全局变量的方法是什么?任何浏览器javascript调试器都可以做到这一点吗?我指的是阅读,而不是更改/添加。如果能检测到iframe,也会很好 请注意: 我需要得到一个全局变量列表“感动”的网站。不是所有的,也不是添加的或编辑的,这些都是在站点脚本的任何地方使用的。在Chrome中,转到开发工具并打开控制台。 然后键入以下内容: Object.keys( window ); 这将为您提供一个包含所有全局变量的数组 const listGlobal = ()=> {

列出站点使用过的所有全局变量的方法是什么?任何浏览器javascript调试器都可以做到这一点吗?我指的是阅读,而不是更改/添加。如果能检测到iframe,也会很好

请注意:
我需要得到一个全局变量列表“感动”的网站。不是所有的,也不是添加的或编辑的,这些都是在站点脚本的任何地方使用的。

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

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
}
编辑

在谷歌上搜索了一下后,我找到了一种方法。您需要firefox插件

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

然后在网页上运行jslinter并在结果中向下滚动。您将有一个未使用变量的列表(每个函数先是全局变量,然后是局部变量)


现在运行
Object.keys(窗口)并比较两者的结果,以确定使用了哪些代码。

将以下代码复制并粘贴到javascript控制台中

var keys = Object.getOwnPropertyNames( window ),
    value;

for( var i = 0; i < keys.length; ++i ) {
    value = window[ keys[ i ] ];
    console.log( value );
}
var keys=Object.getOwnPropertyNames(窗口),
价值
对于(变量i=0;i
所有记入RightSaidFred()的贷方


我希望这对您有所帮助

您可以尝试为此使用getter,您可以为所有现有全局变量创建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.");
        }
    });
});
当然,属性描述符等与旧浏览器不兼容。请注意,有些全局变量/
窗口
属性可能无法以编程方式列出(如*
处理程序上的
),如果需要,必须在数组中显式列出它们。请参见相关问题和


不过,我想运行一个代码覆盖率工具,抱怨未声明的全局变量,就像@stackErro建议的那样,会更有帮助。

你可以尝试使用JetBrains PhpStorm,这就是我所做的,你可以免费获得30天的任何系统试用期。然后检查JSLint或JSHint,或者两者我都不记得了,然后所有未使用的变量都会加下划线,用不同的颜色突出显示(根据主题),并在滚动条上可见,当您将鼠标悬停在它们上方时,会显示未使用的变量

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

因为这个问题是谷歌在搜索如何列出全局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]]);
   }
})();

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

列出我有时使用的全局变量的简单方法。 首先,在执行任何脚本之前,尽可能早地编写此代码

var WINDOW\u PROPS=Object.keys(窗口);
然后,当你需要发现你的全局时,只需这样做:

var GLOBALS=Object.keys(窗口)
//筛选代码未声明的道具
.filter(prop=>WINDOW_PROPS.indexOf(prop)<0)
//美化输出:)这取决于你。。。
.map(prop=>`${typeof window[prop]}${prop}${window[prop]}`)
//按类型和名称排序,以更轻松地找到所需内容
.sort();
console.log(GLOBALS.join(“\n”);

我在这里使用了一些ES6特性来缩短代码。它对生产仍然不好,但对于调试来说已经足够好了,应该可以在现代浏览器中使用。

我所做的是。我找到了一个尽可能少的JavaScript/框架的页面,将它们的所有键记录在数组中。 然后迭代新页面上的所有键,只记录上一个站点中未列出的键。 您可以试试,也可以使用我的代码片段

var ks=[“postMessage”、“blur”、“focus”、“close”、“frames”、“self”、“window”、“parent”、“opener”、“top”、“length”、“closed”、“location”、“document”、“origin”、“name”、“history”、“locationbar”、“menubar”、“personalbar”、“Scrollbar”、“status”、“status”、“frameElement”、“navigator”、“customElements”、“external”、“screen”、“innerWidth”、“innerHeight”、“scrollX”,“pageXOffset”,“screenX”,“pageYOffset”,“screenX”,“screenY”,“outerWidth”,“outerHeight”,“devicePixelRatio”,“clientInformation”,“screenLeft”,“screenTop”,“defaultStatus”,“defaultStatus”,“styleMedia”,“onanimationend”,“onanimationstart”,“onsearch”,“ontransitionend”,“onwebkitanimationend”,“onwebkitanimationiteration”,“onwebkitanimationstart”、“OnWebKittTransitionEnd”、“isSecureContext”、“OnBort”、“onblur”、“oncancel”、“oncanplay”、“oncanplaythrough”、“onchange”、“onclick”、“onclose”、“oncontextmenu”、“oncuechange”、“ondblclick”、“ondragend”、“ondragenter”、“ondragleave”、“ondragover”、“ondragstart”、“ondrop”、“ondurationchange”、“OnEmpted”、“onemptied”、“onerror”、“onfocus”、“onfocus”等”oninput、oninvalid、onkeydown、onkeypress、onkeyup、onload、onloadeddata、onloadstart、onmousedown、onmouseenter、onmouseleave、OnMouseMouseMouse、onmouseout、onmouseover、onmouseup、onmousewheel、onpause、onplay、onplay、onplay、onplay、onprogress、onratechange、onreset、OnResized、onscroll、OnSeek、OnSeek、OnSelection“,”OnInstalled“,”onsubmit“,”onsuspend“,”ontimeupdate“,”OnGoggle“,”onvolumechange“,”onwaiting“,”onwheel“,”OnUxClick“,”ongotpointercapture“,”onpointerdown“,”onpointermove“,”onpointerup“,”onpointerout“,”OnPointerNoter“,”onpointerleave“,”onafterprint“,”onbeforeprint“,”OnBeforeUnforeUnload“,“onhashchange”、“onlanguagechange”、“onmessage”、“onmessageerror”、“onoffline”、“ononline”、“onpagehide”、“onpageshow”、“o”
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
}