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


236

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

Chrome的控制台是否有办法(或至少是一条命令)显示所有公共变量和对象的列表?它将节省大量打字。

Answers:


330

您在寻找这种输出吗?

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

这将列出window对象上所有可用的内容(例如,所有功能和变量,$以及jQuery此页面上的内容,等等)。虽然,这是一个相当大的清单。不确定它有多有用...

否则,只需执行以下操作即可window

window

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


4
@ntownsend-我的控制台与您不同意:) 这是的属性object,为什么没有它?
尼克·克拉弗

9
“为什么没有它?” [[Prototype]]全局对象的内部属性是依赖实现的,在几乎所有主要的实现-V8,Spidermonkey,Rhino等-中,全局对象都从继承Object.prototype,但是例如在其他实现中-JScript,BESEN,DMDScript等。 ..-它不存在,所以window.hasOwnProperty不存在,要对其进行测试,我们可以:Object.prototype.isPrototypeOf(window);
CMS 2010年

10
@CMS-是的,没错...但是问题是关于Chrome的,因此实现是已知的。
尼克·克拉弗

6
或者,您可以只输入一次;
Eddie B

2
我也想看一下变量的值,所以我用了:for(var b in window) { if(window.hasOwnProperty(b)) console.log(b+" = "+window[b]); }
north-bradley

75

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

chrome-globals


2
我可以在不暂停的情况下从执行上下文中吐出var,例如断点秀吗?
2013年

1
@MildFuzz然后使用Nick Craver的解决方案(已接受的解决方案)。
Marcel Korpel 2013年

61

打开控制台,然后输入:

  • keys(window) 看变数
  • dir(window) 看物体

dir(Function("return this")())使其也可以在Web Workers中工作
Janus Troelsen

2
FYI dir(window)在Firefox中不起作用(是的,我知道该线程与Chrome有关),但key(window)在Firefox中却有效
Craig London


31

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

(function(){var standardGlobals=["top","window","location","external","chrome","document","inlineCSS","target","width","height","canvas","data","DOMURL","img","svg","ctx","url","w","a","speechSynthesis","webkitNotifications","localStorage","sessionStorage","applicationCache","webkitStorageInfo","indexedDB","webkitIndexedDB","crypto","CSS","performance","console","devicePixelRatio","styleMedia","parent","opener","frames","self","defaultstatus","defaultStatus","status","name","length","closed","pageYOffset","pageXOffset","scrollY","scrollX","screenTop","screenLeft","screenY","screenX","innerWidth","innerHeight","outerWidth","outerHeight","offscreenBuffering","frameElement","clientInformation","navigator","toolbar","statusbar","scrollbars","personalbar","menubar","locationbar","history","screen","postMessage","close","blur","focus","ondeviceorientation","ondevicemotion","onunload","onstorage","onresize","onpopstate","onpageshow","onpagehide","ononline","onoffline","onmessage","onhashchange","onbeforeunload","onwaiting","onvolumechange","ontimeupdate","onsuspend","onsubmit","onstalled","onshow","onselect","onseeking","onseeked","onscroll","onreset","onratechange","onprogress","onplaying","onplay","onpause","onmousewheel","onmouseup","onmouseover","onmouseout","onmousemove","onmouseleave","onmouseenter","onmousedown","onloadstart","onloadedmetadata","onloadeddata","onload","onkeyup","onkeypress","onkeydown","oninvalid","oninput","onfocus","onerror","onended","onemptied","ondurationchange","ondrop","ondragstart","ondragover","ondragleave","ondragenter","ondragend","ondrag","ondblclick","oncuechange","oncontextmenu","onclose","onclick","onchange","oncanplaythrough","oncanplay","oncancel","onblur","onabort","onwheel","onwebkittransitionend","onwebkitanimationstart","onwebkitanimationiteration","onwebkitanimationend","ontransitionend","onsearch","getSelection","print","stop","open","showModalDialog","alert","confirm","prompt","find","scrollBy","scrollTo","scroll","moveBy","moveTo","resizeBy","resizeTo","matchMedia","requestAnimationFrame","cancelAnimationFrame","webkitRequestAnimationFrame","webkitCancelAnimationFrame","webkitCancelRequestAnimationFrame","captureEvents","releaseEvents","atob","btoa","setTimeout","clearTimeout","setInterval","clearInterval","TEMPORARY","PERSISTENT","getComputedStyle","getMatchedCSSRules","webkitConvertPointFromPageToNode","webkitConvertPointFromNodeToPage","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","openDatabase","addEventListener","removeEventListener","dispatchEvent"];
    var appSpecificGlobals={};
    for (var w in window){
        if (standardGlobals.indexOf(w)==-1) appSpecificGlobals[w]=window[w];
    }
    console.log(appSpecificGlobals);})()

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

javascript:(function(){var standardGlobals=["top","window","location","external","chrome","document","inlineCSS","target","width","height","canvas","data","DOMURL","img","svg","ctx","url","w","a","speechSynthesis","webkitNotifications","localStorage","sessionStorage","applicationCache","webkitStorageInfo","indexedDB","webkitIndexedDB","crypto","CSS","performance","console","devicePixelRatio","styleMedia","parent","opener","frames","self","defaultstatus","defaultStatus","status","name","length","closed","pageYOffset","pageXOffset","scrollY","scrollX","screenTop","screenLeft","screenY","screenX","innerWidth","innerHeight","outerWidth","outerHeight","offscreenBuffering","frameElement","clientInformation","navigator","toolbar","statusbar","scrollbars","personalbar","menubar","locationbar","history","screen","postMessage","close","blur","focus","ondeviceorientation","ondevicemotion","onunload","onstorage","onresize","onpopstate","onpageshow","onpagehide","ononline","onoffline","onmessage","onhashchange","onbeforeunload","onwaiting","onvolumechange","ontimeupdate","onsuspend","onsubmit","onstalled","onshow","onselect","onseeking","onseeked","onscroll","onreset","onratechange","onprogress","onplaying","onplay","onpause","onmousewheel","onmouseup","onmouseover","onmouseout","onmousemove","onmouseleave","onmouseenter","onmousedown","onloadstart","onloadedmetadata","onloadeddata","onload","onkeyup","onkeypress","onkeydown","oninvalid","oninput","onfocus","onerror","onended","onemptied","ondurationchange","ondrop","ondragstart","ondragover","ondragleave","ondragenter","ondragend","ondrag","ondblclick","oncuechange","oncontextmenu","onclose","onclick","onchange","oncanplaythrough","oncanplay","oncancel","onblur","onabort","onwheel","onwebkittransitionend","onwebkitanimationstart","onwebkitanimationiteration","onwebkitanimationend","ontransitionend","onsearch","getSelection","print","stop","open","showModalDialog","alert","confirm","prompt","find","scrollBy","scrollTo","scroll","moveBy","moveTo","resizeBy","resizeTo","matchMedia","requestAnimationFrame","cancelAnimationFrame","webkitRequestAnimationFrame","webkitCancelAnimationFrame","webkitCancelRequestAnimationFrame","captureEvents","releaseEvents","atob","btoa","setTimeout","clearTimeout","setInterval","clearInterval","TEMPORARY","PERSISTENT","getComputedStyle","getMatchedCSSRules","webkitConvertPointFromPageToNode","webkitConvertPointFromNodeToPage","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","openDatabase","addEventListener","removeEventListener","dispatchEvent"]; var $appSpecificGlobals={};for (var w in window){if (standardGlobals.indexOf(w)==-1) $appSpecificGlobals[w]=window[w];} window.$appSpecificGlobals=$appSpecificGlobals;console.log(window.$appSpecificGlobals);})()

2
这是当前Chrome和Firefox默认全局变量的列表:pastebin.com/wNj3kfg0
redaxmedia 2014年

9

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 现在只有全局变量。


1
prop.toString似乎并非到处都存在,所以情况可能更具防御性if(window.hasOwnProperty(b) && prop && (prop.toString && !prop.toString().includes('native code')) && !standardGlobals.includes(b))
Yves Amsellem

6

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

debugger

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

说句公道话,你会得到一切window范围,包括浏览器的内置插件,所以它可能是某种针-IN-A-草垛体验。:/


4

您可能需要尝试Chrome的Firebug lite扩展。


3
虽然看起来不错,但此解决方案听起来有点用大炮杀死了我的一只蚊子。
Marcel Korpel

也许。这是我发现的唯一显示对象/功能/等的东西。FF中Firebug的执行方式(在扩展名的DOM-tab中)。不过有点慢。
KooiInc

1
截至5月17日,您的链接已断开。一样吗 getfirebug.com/releases/lite/chrome
伊恩·亨特

@beanland 7:是的,在答案中进行了修正,警告警告
KooiInc 2012年

4

要查看chrome中的任何变量,请转到“源”,然后单击“监视”并添加它。如果在此处添加“窗口”变量,则可以展开并浏览。


4

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);
})();



1

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



0

列出变量及其值

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的回答


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.