Ver lista de todas las variables de JavaScript en Google Chrome Console


En Firebug, la pestaña DOM muestra una lista de todas las variables y objetos públicos. En la consola de Chrome tienes que escribir el nombre de la variable pública u objeto que desea explorar.

Hay una manera - o al menos un comando - para la consola de Chrome para mostrar una lista de todas las variables públicas y objetos? Ahorrará mucho tiempo escribiendo.

Author: Charles, 2010-05-29

12 answers

Es este el tipo de salida que estás buscando?

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

Esto listará todo lo disponible en el objeto window (todas las funciones y variables, por ejemplo, $ y jQuery en esta página, etc.). Sin embargo, esta es toda una lista; no estoy seguro de lo útil que es...

De lo contrario, simplemente haga window y comience a bajar su árbol:

window

Esto le dará DOMWindow, un objeto expandible/explorable.

 258
Author: Nick Craver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-15 14:52:51

Cuando se detiene la ejecución del script (por ejemplo, en un punto de interrupción), simplemente puede ver todas las globales en el panel derecho de la ventana de Herramientas para desarrolladores:

chrome-globals

 66
Author: Marcel Korpel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-08 14:26:09

Abra la consola y luego ingrese:

  • keys(window) para ver variables
  • dir(window) para ver objetos
 46
Author: arkadiusm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-24 20:26:01

El objeto window contiene todas las variables públicas, por lo que puede escribirlo en la consola y luego expandirlo para ver todas las variables/atributos/funciones.

chrome-show-all-variables-expand-window-object

 34
Author: Fabien Ménager,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-24 02:55:15

Si desea excluir todas las propiedades estándar del objeto window y las vistas globales específicas de la aplicación, esto las imprimirá en la consola de 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);})()

El script funciona bien como un bookmarklet. Para usar el script como bookmarklet, cree un nuevo marcador y reemplace la URL con lo siguiente:

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);})()
 29
Author: Max Heiber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-15 16:26:38

David Walsh tiene una buena solución para esto. Aquí está mi opinión sobre esto, combinando su solución con lo que se ha descubierto en este hilo también.

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 ahora solo tiene los globales.

 6
Author: Avindra Goolcharan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-29 19:47:41

Es posible que desee probar esta Firebug lite extensión para Chrome.

 4
Author: KooiInc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-18 06:15:59

Para ver cualquier variable en chrome, vaya a "Sources", y luego a "Watch" y agréguela. Si agrega la variable" ventana " aquí, puede expandirla y explorarla.

 3
Author: TigerBear,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-16 07:38:04

Método actualizado del mismo artículo Avindra mentioned - inyecta iframe y compara sus propiedades contentWindow con las propiedades de la ventana global.

(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);
})();
 3
Author: jmsmrgn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-04 06:59:03

Como todas las "variables públicas" son de hecho propiedades del objeto window (de la ventana/pestaña que está mirando), puede inspeccionar el objeto "window" en su lugar. Si tiene varios marcos, tendrá que seleccionar el objeto de ventana correcto (como en Firebug) de todos modos.

 1
Author: mihi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-29 11:28:03

introduzca la descripción de la imagen aquí

 1
Author: GRboss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-03 08:31:29

Escriba la siguiente instrucción en la consola javascript:

debugger

Ahora puede inspeccionar el ámbito global usando las herramientas de depuración normales.

Para ser justos, obtendrás todo en el ámbito window, incluidos los incorporados en el navegador, por lo que podría ser una especie de experiencia de aguja en un pajar. :/

 0
Author: tangentstorm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-27 13:58:33