Lihat daftar semua variabel JavaScript di Google Chrome Console

237

Di Firebug, tab DOM menampilkan daftar semua variabel dan objek publik Anda. Di konsol Chrome, Anda harus mengetik nama variabel publik atau objek yang ingin Anda jelajahi.

Apakah ada cara - atau setidaknya perintah - untuk konsol Chrome untuk menampilkan daftar semua variabel dan objek publik? Ini akan menghemat banyak pengetikan.

GRboss
sumber

Jawaban:

330

Apakah ini jenis output yang Anda cari?

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

Ini akan mencantumkan semua yang tersedia pada windowobjek (semua fungsi dan variabel, misalnya, $dan jQuerypada halaman ini, dll.). Padahal, ini daftar yang cukup; tidak yakin seberapa membantu itu ...

Kalau tidak, lakukan saja windowdan mulai turun pohonnya:

window

Ini akan memberi Anda DOMWindow, objek yang dapat diperluas / dieksplorasi.

Nick Craver
sumber
4
@ntownsend -Konsol saya tidak setuju dengan Anda :) Ini propertiobject , mengapa tidak memilikinya?
Nick Craver
9
"Kenapa tidak memilikinya?" The [[Prototype]]properti internal obyek global adalah tergantung implementasi , di hampir semua implementasi utama -V8, Spidermonkey, Rhino, dll-, mewarisi obyek global di beberapa titik dari Object.prototype, tapi misalnya dalam implementasi lainnya -JScript, Besen, DMDScript, dll ..- tidak, jadi window.hasOwnPropertytidak ada, untuk mengujinya kita dapat:Object.prototype.isPrototypeOf(window);
CMS
10
@CMS - Ya itu benar ... tetapi pertanyaannya khusus tentang Chrome, sehingga implementasinya diketahui.
Nick Craver
6
Atau Anda bisa mengetik ini;
Eddie B
2
Saya ingin melihat nilai variabel juga jadi saya menggunakan:for(var b in window) { if(window.hasOwnProperty(b)) console.log(b+" = "+window[b]); }
north-bradley
75

Ketika eksekusi skrip dihentikan (misalnya, pada breakpoint) Anda bisa melihat semua global di panel kanan jendela Tools Developer:

chrome-global

Marcel Korpel
sumber
2
dapatkah saya memuntahkan vars dari konteks eksekusi, seperti acara break point, tanpa berhenti?
Mild Fuzz
1
@MildFuzz Kemudian gunakan solusi Nick Craver (yang diterima).
Marcel Korpel
62

Buka konsol dan kemudian masukkan:

  • keys(window) untuk melihat variabel
  • dir(window) untuk melihat objek
arkadiusm
sumber
dir(Function("return this")())membuatnya bekerja di Web Pekerja juga
Janus Troelsen
2
FYI dir(window)tidak bekerja di Firefox (ya saya tahu utas ini tentang Chrome), tetapi key(window)bekerja di Firefox
Craig London
38

The windowobjek berisi semua variabel publik, sehingga Anda dapat mengetik di konsol dan kemudian memperluas untuk melihat semua variabel / atribut / fungsi.

chrome-show-all-variable-expand-window-object

Fabien Ménager
sumber
4
Bagus! Sejauh ini cara termudah karena Anda dapat memperluas variabel secara rekursif.
qwertzguy
31

Jika Anda ingin mengecualikan semua properti standar objek jendela dan melihat global spesifik aplikasi, ini akan mencetaknya ke konsol 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);})()

Script berfungsi dengan baik sebagai bookmarklet. Untuk menggunakan skrip sebagai bookmarklet, buat bookmark baru dan ganti URL dengan yang berikut:

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);})()
Max Heiber
sumber
2
Ini adalah daftar global Chrome standar dan Firefox saat ini: pastebin.com/wNj3kfg0
redaxmedia
9

David Walsh memiliki solusi yang bagus untuk ini. Inilah pendapat saya tentang ini, menggabungkan solusinya dengan apa yang telah ditemukan di utas ini juga.

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 sekarang hanya memiliki global.

Avindra Goolcharan
sumber
1
prop.toStringtampaknya tidak ada di mana-mana, jadi kondisinya bisa lebih defensifif(window.hasOwnProperty(b) && prop && (prop.toString && !prop.toString().includes('native code')) && !standardGlobals.includes(b))
Yves amsellem
6

Ketikkan pernyataan berikut di konsol javascript:

debugger

Sekarang Anda dapat memeriksa ruang lingkup global menggunakan alat debug normal.

Agar adil, Anda akan mendapatkan semua yang ada di windowruang lingkup, termasuk browser bawaan, jadi itu mungkin semacam pengalaman jarum-in-a-tumpukan jerami. : /

badai singgung
sumber
4

Anda mungkin ingin mencoba ekstensi Firebug lite ini untuk Chrome.

KooiInc
sumber
3
Meskipun terlihat bagus, solusi ini kedengarannya sedikit menggunakan meriam untuk membunuh nyamuk bagi saya.
Marcel Korpel
Mungkin. Ini satu-satunya hal yang saya temukan yang menunjukkan objek / fungsi / dll. cara pembakar di FF tidak (di bawah tab DOM di ekstensi). Tapi agak lambat.
KooiInc
1
Mulai 17 Mei, tautan Anda rusak. Apakah ini sama? getfirebug.com/releases/lite/chrome
Ian Hunter
@beanland 7: ya, perbaiki dalam jawaban, thnx untuk peringatan
KooiInc
4

Untuk melihat variabel apa pun di chrome, buka "Sumber", lalu "Tonton" dan tambahkan. Jika Anda menambahkan variabel "jendela" di sini maka Anda dapat mengembangkannya dan menjelajah.

TigerBear
sumber
4

Metode yang diperbarui dari artikel yang sama yang disebutkan Avindra - menyuntikkan iframe dan membandingkan contentWindowpropertinya dengan properti jendela 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);
})();

James Morgan
sumber
2

Ketik: thisdi konsol,

untuk mendapatkan window objectI think (?), saya pikir pada dasarnya sama dengan mengetik windowdi konsol.

Ini berfungsi setidaknya di Firefox & chrome.

Sebastian Norr
sumber
1

Karena semua "variabel publik" sebenarnya adalah properti dari objek jendela (dari jendela / tab yang Anda lihat), Anda dapat memeriksa objek "jendela" saja. Jika Anda memiliki banyak bingkai, Anda harus memilih objek jendela yang benar (seperti di Firebug).

mihi
sumber
1

Coba perintah sederhana ini:

console.log (jendela)
Vaclav Muller
sumber
Ia mengembalikan "tidak terdefinisi"
Shayan
0

Daftar variabel dan nilainya

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

masukkan deskripsi gambar di sini

Menampilkan nilai objek variabel tertentu

console.log(JSON.stringify(content_of_some_variable_object))

masukkan deskripsi gambar di sini

Sumber: komentar dari @ north-bradley dan jawaban dari @ nick-craver

intika
sumber