web-dev-qa-db-fra.com

Afficher la liste de toutes les variables JavaScript dans la console Google Chrome

Dans Firebug, l'onglet DOM affiche une liste de toutes vos variables et objets publics. Dans la console de Chrome, vous devez taper le nom de la variable publique ou de l'objet à explorer.

Existe-t-il un moyen - ou au moins une commande - permettant à la console de Chrome d’afficher une liste de toutes les variables et objets publics? Cela vous évitera beaucoup de dactylographie.

204
GRboss

Est-ce le type de sortie que vous recherchez?

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

Ceci listera tout ce qui est disponible sur l’objet window (toutes les fonctions et variables, par exemple, $ et jQuery sur cette page, etc.). Bien que, ceci est une liste; je ne sais pas à quel point c'est utile ...

Sinon, faites juste window et commencez à descendre son arbre:

window

Cela vous donnera DOMWindow, un objet extensible/explorable.

275
Nick Craver

Lorsque l'exécution du script est interrompue (sur un point d'arrêt, par exemple), vous pouvez simplement afficher tous les éléments globaux dans le volet de droite de la fenêtre Outils de développement:

chrome-globals

68
Marcel Korpel

Ouvrez la console puis entrez:

  • keys(window) pour voir les variables
  • dir(window) pour voir les objets 
49
arkadiusm

L'objet window contient toutes les variables publiques. Vous pouvez donc le saisir dans la console, puis le développer pour afficher toutes les variables/attributs/fonctions. 

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

34
Fabien Ménager

Si vous souhaitez exclure toutes les propriétés standard de l'objet window et afficher les globales spécifiques à l'application, cela les imprimera sur la console 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);})()

Le script fonctionne bien comme un bookmarklet. Pour utiliser le script en tant que bookmarklet, créez un nouveau signet et remplacez l'URL par le texte suivant:

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
Max Heiber

David Walsh a une solution intéressante pour cela. Voici mon point de vue, combinant sa solution avec ce qui a été découvert sur ce fil également.

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 a maintenant que les globals.

7
Avindra Goolcharan

Vous voudrez peut-être essayer cette extension Firebug lite pour Chrome.

4
KooiInc

Pour afficher une variable en chrome, allez dans "Sources", puis "Regarder" et ajoutez-le. Si vous ajoutez la variable "fenêtre" ici, vous pouvez la développer et l'explorer.

3
TigerBear

Méthode mise à jour de same article Avindra mentionne - injecte iframe et compare ses propriétés contentWindow aux propriétés de la fenêtre globale.

(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
jmsmrgn

Comme toutes les "variables publiques" sont en fait des propriétés de l'objet window (de la fenêtre/de l'onglet que vous regardez), vous pouvez simplement inspecter l'objet "window" Si vous avez plusieurs cadres, vous devrez quand même sélectionner le bon objet window (comme dans Firebug).

1
mihi

Tapez: this dans la console,

pour obtenir le window object je pense (?), je pense que c'est fondamentalement la même chose que taper window dans la console.

Cela fonctionne au moins dans Firefox et chrome.

1
Sebastian Norr

enter image description here

1
GRboss

Essayez cette commande simple:

console.log (fenêtre)
1
Vaclav Muller

Tapez l'instruction suivante dans la console javascript:

debugger

Vous pouvez maintenant inspecter l'étendue globale à l'aide des outils de débogage normaux.

Pour être juste, vous obtiendrez tout dans la portée window, y compris dans le navigateur intégré, de sorte qu’il s’agit peut-être d’une expérience difficile. : /

0
tangentstorm