programing

Google Chrome Console에서 모든 JavaScript 변수 목록 보기

coolbiz 2022. 9. 28. 23:05
반응형

Google Chrome Console에서 모든 JavaScript 변수 목록 보기

Firebug에서 DOM 탭은 모든 공용 변수와 개체의 목록을 표시합니다.Chrome 콘솔에서 탐색할 공용 변수 또는 개체의 이름을 입력해야 합니다.

Chrome의 콘솔이 모든 공용 변수와 오브젝트 목록을 표시할 수 있는 방법(또는 적어도 명령어)이 있습니까?타이핑을 많이 줄일 수 있습니다.

이런 종류의 출력을 원하십니까?

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

그러면 에서 사용할 수 있는 모든 것이 나열됩니다.window객체(모든 함수 및 변수, 예를 들어$그리고.jQuery(이 페이지 등)에 기재되어 있습니다.하지만, 이건 꽤 많은 목록이에요. 얼마나 도움이 될지는 모르겠지만...

그렇지 않으면 그냥 해window나무 아래로 내려가기 시작합니다.

window

이것으로 알 수 있습니다.DOMWindow확장 가능/익스플로러블 오브젝트.

스크립트 실행이 정지된 경우(예를 들어 중단점), [Developer Tools]창 오른쪽 페인으로 모든 글로벌을 표시할 수 있습니다.

chrome-globals

콘솔을 열고 다음을 입력합니다.

  • keys(window)변수를 보다
  • dir(window)사물을 보다

windowobject에는 모든 공용 변수가 포함되어 있으므로 콘솔에 입력한 후 확장하여 모든 변수/속성/변수를 표시할 수 있습니다.

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

윈도 객체의 모든 표준 속성을 제외하여 응용 프로그램별 글로벌을 표시하는 경우 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)
        }
    }
})()

Javascript 콘솔에 다음 문을 입력합니다.

debugger

이제 일반 디버깅툴을 사용하여 글로벌스코프를 검사할 수 있게 되었습니다.

공정하게 말하면, 모든 을 얻을 수 있습니다.window브라우저의 빌트인을 포함한 스코프이기 때문에 니들 인 어 멀티스택 익스피리언스라고 할 수 있습니다.:/

데이비드 월시가 좋은 해결책을 가지고 있어요여기에 그의 솔루션을 이 스레드에서 발견한 것과 결합하는 나의 견해가 있다.

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이제 지구촌만 남았지

Chrome 변수를 보려면 "Sources"로 이동한 다음 "Watch"로 이동하여 추가합니다.여기에 "창" 변수를 추가하면 변수를 확장하고 탐색할 수 있습니다.

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

★★★★★this「」에서,

을 받다window object제에(?)를 입력하는 것 요.window콘솔로 이동합니다.

적어도 파이어폭스나 크롬에서는 동작합니다.

Chrome용 Firebug Lite 확장을 사용해 보십시오.

디버깅을 위해 이 기능을 종료했습니다.

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

try 피할 때 합니다.TypeError: Converting circular structure to JSON
★★★★★★★★★★★★★★★.Save as...콘솔 출력을 파일로 변환하고 더 조작합니다.

변수 및 변수 값 나열

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

enter image description here

특정 변수 객체의 값을 표시합니다.

console.log(JSON.stringify(content_of_some_variable_object))

enter image description here

출처 : @northern-bradley로부터의 코멘트 및 @nick-craver로부터의 답변

모든 "퍼블릭 변수"는 실제로는 (보고 있는 창/탭의) 창 객체의 속성이기 때문에 대신 "창" 객체를 검사할 수 있습니다.프레임이 여러 개 있는 경우 Firebug와 같은 올바른 창 개체를 선택해야 합니다.

다음 간단한 명령을 사용해 보십시오.

console.log(표준)

enter image description here

언급URL : https://stackoverflow.com/questions/2934787/view-list-of-all-javascript-variables-in-google-chrome-console

반응형