在 Google Chrome 控制台中查看所有 JavaScript 变量的列表

Posted

技术标签:

【中文标题】在 Google Chrome 控制台中查看所有 JavaScript 变量的列表【英文标题】:View list of all JavaScript variables in Google Chrome Console 【发布时间】:2011-02-25 11:03:42 【问题描述】:

在 Firebug 中,DOM 选项卡显示所有公共变量和对象的列表。在 Chrome 的控制台中,您必须输入要探索的公共变量或对象的名称。

有没有办法——或者至少是一个命令——让 Chrome 的控制台显示所有公共变量和对象的列表?这将节省大量的打字时间。

【问题讨论】:

【参考方案1】:

我已将其用于调试目的:

for (aProperty in window) 
    try
        console.log(aProperty +':'+JSON.stringify(window[aProperty]));
    catch

try 用于避开TypeError: Converting circular structure to JSON 然后Save as...控制台输出到一个文件并进一步操作。

【讨论】:

【参考方案2】:

如果您想排除窗口对象的所有标准属性并查看特定于应用程序的全局变量,这会将它们打印到 Chrome 控制台:



    const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "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", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "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", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);

    for (const key of Object.keys(window)) 
        if (!standardGlobals.has(key)) 
            console.log(key)
        
    

该脚本可以很好地用作书签。要将脚本用作书签,请创建一个新书签并将 URL 替换为以下内容:

javascript:(() => 
    const standardGlobals = new Set(["window", "self", "document", "name", "location", "customElements", "history", "locationbar", "menubar", "personalbar", "scrollbars", "statusbar", "toolbar", "status", "closed", "frames", "length", "top", "opener", "parent", "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", "performance", "onappinstalled", "onbeforeinstallprompt", "crypto", "indexedDB", "webkitStorageInfo", "sessionStorage", "localStorage", "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", "ontransitionrun", "ontransitionstart", "ontransitionend", "ontransitioncancel", "onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onlanguagechange", "onmessage", "onmessageerror", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onrejectionhandled", "onstorage", "onunhandledrejection", "onunload", "alert", "atob", "blur", "btoa", "cancelAnimationFrame", "cancelIdleCallback", "captureEvents", "clearInterval", "clearTimeout", "close", "confirm", "createImageBitmap", "fetch", "find", "focus", "getComputedStyle", "getSelection", "matchMedia", "moveBy", "moveTo", "open", "postMessage", "print", "prompt", "queueMicrotask", "releaseEvents", "requestAnimationFrame", "requestIdleCallback", "resizeBy", "resizeTo", "scroll", "scrollBy", "scrollTo", "setInterval", "setTimeout", "stop", "webkitCancelAnimationFrame", "webkitRequestAnimationFrame", "chrome", "caches", "ondevicemotion", "ondeviceorientation", "ondeviceorientationabsolute", "originAgentCluster", "cookieStore", "showDirectoryPicker", "showOpenFilePicker", "showSaveFilePicker", "speechSynthesis", "onpointerrawupdate", "trustedTypes", "crossOriginIsolated", "openDatabase", "webkitRequestFileSystem", "webkitResolveLocalFileSystemURL"]);
    for (const key of Object.keys(window)) 
        if (!standardGlobals.has(key)) 
            console.log(key)
        
    
)()

【讨论】:

这是当前 Chrome 和 Firefox 默认全局变量的列表:pastebin.com/wNj3kfg0 不幸的是一个过时的列表,但仍然非常有用!如果我有更多时间,我会贡献一种方法,以一种简单的方式在空白窗口中获取当前的 standardGlobals(在几个小时内提醒我,我应该有一些时间,以防有人感兴趣并且不能做它自己)。 2021 年更新,但其他一些答案似乎常青。【参考方案3】:

列出变量及其值

for(var b in window)  if(window.hasOwnProperty(b)) console.log(b+" = "+window[b]); 

显示特定变量对象的值

console.log(JSON.stringify(content_of_some_variable_object))

来源:@northern-bradley 的评论和@nick-craver 的回答

【讨论】:

【参考方案4】:

在控制台中输入:this

我想得到window object(?),我认为它与在控制台中输入window基本相同。

它至少在 Firefox 和 chrome 中有效。

【讨论】:

【参考方案5】:

试试这个简单的命令:

console.log(窗口)

【讨论】:

返回“未定义”【参考方案6】:

在 javascript 控制台中键入以下语句:

debugger

现在您可以使用常规调试工具检查全局范围。

公平地说,您将在window 范围内获得所有内容,包括浏览器内置插件,因此这可能是一种大海捞针的体验。 :/

【讨论】:

【参考方案7】:

这是您正在寻找的输出类型吗?

for(var b in window)  
  if(window.hasOwnProperty(b)) console.log(b); 

这将列出window 对象上可用的所有内容(所有函数和变量,例如,此页面上的$jQuery 等)。不过,这是一个相当多的清单;不知道有多大帮助...

否则只需执行window 并开始顺着它的树向下走:

window

这将为您提供DOMWindow,一个可展开/可探索的对象。

【讨论】:

@ntownsend - 我的控制台不同意你的观点 :) It's a property of object,为什么没有呢? "为什么没有它?"全局对象的[[Prototype]] 内部属性依赖于实现,在几乎所有主要实现中-V8、Spidermonkey、Rhino 等-,全局对象在某些时候继承自Object.prototype,但对于其他实现中的示例 -JScript、BESEN、DMDScript 等...- 它不存在,因此 window.hasOwnProperty 不存在,我们可以对其进行测试:Object.prototype.isPrototypeOf(window); @CMS - 是的,这是真的……但问题是专门针对 Chrome 的,所以实现是已知的。 或者你可以输入这个; 我也想查看变量的值,所以我使用了:for(var b in window) if(window.hasOwnProperty(b)) console.log(b+" = "+window[b]); 【参考方案8】:

打开控制台,然后输入:

keys(window)查看变量 dir(window)查看对象

【讨论】:

dir(Function("return this")()) 也可以在 Web Workers 中使用 仅供参考 dir(window) 在 Firefox 中不起作用(是的,我知道这个线程是关于 Chrome 的),但 key(window) 在 Firefox 中起作用【参考方案9】:

从提到的 article Avindra 更新方法 — 注入 iframe 并将其 contentWindow 属性与全局窗口属性进行比较。

(function() 
  var iframe = document.createElement('iframe');
  iframe.onload = function() 
    var iframeKeys = Object.keys(iframe.contentWindow);
    Object.keys(window).forEach(function(key) 
      if(!(iframeKeys.indexOf(key) > -1)) 
        console.log(key);
      
    );
  ;
  iframe.src = 'about:blank';
  document.body.appendChild(iframe);
)();

【讨论】:

【参考方案10】:

要查看 chrome 中的任何变量,请转到“Sources”,然后转到“Watch”并添加它。如果在此处添加“window”变量,则可以展开并探索。

【讨论】:

【参考方案11】:

David Walsh 对此有一个很好的解决方案。这是我对此的看法,将他的解决方案与在这个线程上发现的内容结合起来。

https://davidwalsh.name/global-variables-javascript

x = ;
var iframe = document.createElement('iframe');
iframe.onload = function() 
    var standardGlobals = Object.keys(iframe.contentWindow);
    for(var b in window)  
      const prop = window[b];
      if(window.hasOwnProperty(b) && prop && !prop.toString().includes('native code') && !standardGlobals.includes(b)) 
        x[b] = prop;
      
    
    console.log(x)
;
iframe.src = 'about:blank';
document.body.appendChild(iframe);

x 现在只有全局变量。

【讨论】:

prop.toString 似乎并非无处不在,因此条件可能更具防御性if(window.hasOwnProperty(b) && prop && (prop.toString && !prop.toString().includes('native code')) && !standardGlobals.includes(b))【参考方案12】:

window 对象包含所有公共变量,因此您可以在控制台中键入它,然后展开以查看所有变量/属性/函数。

【讨论】:

不错!迄今为止最简单的方法,因为您可以递归扩展变量。 这是查看document 的好方法,就像浏览器通过元素查看document. document(dot) 一样查看文档属性。 window.document 澄清了很多关于 window vs document 的困惑【参考方案13】:

您可能想试试这个适用于 Chrome 的 Firebug lite 扩展程序。

【讨论】:

虽然看起来不错,但这个解决方案对我来说听起来有点像用大炮杀死蚊子。 也许吧。这是我发现的唯一显示对象/功能/等的东西。 FF 中的 firebug 的方式(在扩展中的 DOM-tab 下)。不过速度有点慢。 截至 5 月 17 日,您的链接已损坏。这是一样的吗? getfirebug.com/releases/lite/chrome @beanland 7:是的,在答案中修复了它,thnx 警告【参考方案14】:

当脚本执行停止时(例如,在断点处),您可以简单地在开发者工具窗口的右窗格中查看所有全局变量:

【讨论】:

我可以在不暂停的情况下从执行上下文中吐出变量吗,就像断点秀一样? @MildFuzz 然后使用 Nick Craver 的解决方案(被接受的)。【参考方案15】:

由于所有“公共变量”实际上都是窗口对象(您正在查看的窗口/选项卡)的属性,因此您可以只检查“窗口”对象。如果您有多个框架,则无论如何都必须选择正确的窗口对象(如在 Firebug 中)。

【讨论】:

以上是关于在 Google Chrome 控制台中查看所有 JavaScript 变量的列表的主要内容,如果未能解决你的问题,请参考以下文章

查找导致在 Google Chrome 中显示水平滚动条的元素

“失败 - 网络错误” - 尝试下载PDF但我可以在最新的Google Chrome(V62x)中查看PDF

怎样卸载google chrome浏览器

如何在 Google Chrome 中关闭 Preserve JavaScript console perseverance

查看http请求的header信息

如何在 Google Chrome 中检查 XMPP 调用