IT이야기

Chrome에 이미 '$'가 정의되어 있는 것일까

cyworld 2021. 3. 21. 09:04
반응형

Chrome에 이미 '$'가 정의되어 있습니까?


스크립트가없는 일반 html 페이지의 Chrome 콘솔에 $를 입력하면. 이 출력을 볼 수 있습니다.

> $
< bound(selector, startNode)

그러나 window. $ 할 때 출력은 정의되지 않습니다.

> window.$
< undefined

여기서 정의 된 $는 무엇이며 개체를 통해 액세스 할 수없는 이유는 window무엇입니까?


$코드를 래핑 __commandLineAPI하는 with문을 통해 개체 에서 콘솔에 삽입 된 로컬 변수입니다 (이것이 전역 변수가 아닌 이유입니다). 더 자세히 살펴보면 (예 debugger; $('*');:) 기본적으로 다음 소스를 사용하여 현재 창에 바인딩 된 함수임을 알 수 있습니다.

$: function (selector, opt_startNode) {
    if (this._canQuerySelectorOnNode(opt_startNode))
        return opt_startNode.querySelector(selector);

    return inspectedWindow.document.querySelector(selector);
}

(에 정의 됨 CommandLineAPIImpl.prototype)


에서 명령 줄 API 참조 :

Command Line API는 Chrome 개발자 도구로 일반적인 작업을 수행하기위한 함수 모음입니다. 여기에는 DOM에서 요소를 선택하고 검사하는 편리한 기능이 포함됩니다.

$ (selector) 지정된 CSS 선택기를 사용하여 첫 번째 DOM 요소에 대한 참조를 반환합니다.이 함수는 document.querySelector () 함수의 별칭입니다.

예를 들면 :

$('body')

이전 답변에 추가하면 크롬의 VM 코드에서 찾을 수 있습니다.

// NOTE: Please keep the list of API methods below snchronized to that in WebInspector.RuntimeModel!
// NOTE: Argument names of these methods will be printed in the console, so use pretty names!
/**
 * @type {!Array.<string>}
 * @const
 */
CommandLineAPI.members_ = [
    "$", "$$", "$x", "dir", "dirxml", "keys", "values", "profile", "profileEnd",
    "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear", "getEventListeners",
    "debug", "undebug", "monitor", "unmonitor", "table"
];

모든 구현은 여기에서 찾을 수 있습니다.

CommandLineAPIImpl.prototype = {
    /**
     * @param {string} selector
     * @param {!Node=} opt_startNode
     * @return {*}
     */
    $: function (selector, opt_startNode)
    {
        if (this._canQuerySelectorOnNode(opt_startNode))
            return opt_startNode.querySelector(selector);

        return inspectedWindow.document.querySelector(selector);
    },

    /**
     * @param {string} selector
     * @param {!Node=} opt_startNode
     * @return {*}
     */
    $$: function (selector, opt_startNode)
    {
        if (this._canQuerySelectorOnNode(opt_startNode))
            return opt_startNode.querySelectorAll(selector);
        return inspectedWindow.document.querySelectorAll(selector);
    },

    /**
     * @param {!Node=} node
     * @return {boolean}
     */
    _canQuerySelectorOnNode: function(node)
    {
        return !!node && InjectedScriptHost.subtype(node) === "node" && (node.nodeType === Node.ELEMENT_NODE || node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE);
    },

    /**
     * @param {string} xpath
     * @param {!Node=} opt_startNode
     * @return {*}
     */
    $x: function(xpath, opt_startNode)
    {
        var doc = (opt_startNode && opt_startNode.ownerDocument) || inspectedWindow.document;
        var result = doc.evaluate(xpath, opt_startNode || doc, null, XPathResult.ANY_TYPE, null);
        switch (result.resultType) {
        case XPathResult.NUMBER_TYPE:
            return result.numberValue;
        case XPathResult.STRING_TYPE:
            return result.stringValue;
        case XPathResult.BOOLEAN_TYPE:
            return result.booleanValue;
        default:
            var nodes = [];
            var node;
            while (node = result.iterateNext())
                push(nodes, node);
            return nodes;
        }
    },

    /**
     * @return {*}
     */
    dir: function(var_args)
    {
        return InjectedScriptHost.callFunction(inspectedWindow.console.dir, inspectedWindow.console, slice(arguments));
    },

    /**
     * @return {*}
     */
    dirxml: function(var_args)
    {
        return InjectedScriptHost.callFunction(inspectedWindow.console.dirxml, inspectedWindow.console, slice(arguments));
    },

    /**
     * @return {!Array.<string>}
     */
    keys: function(object)
    {
        return Object.keys(object);
    },

    /**
     * @return {!Array.<*>}
     */
    values: function(object)
    {
        var result = [];
        for (var key in object)
            push(result, object[key]);
        return result;
    },

    /**
     * @return {*}
     */
    profile: function(opt_title)
    {
        return InjectedScriptHost.callFunction(inspectedWindow.console.profile, inspectedWindow.console, slice(arguments));
    },

    /**
     * @return {*}
     */
    profileEnd: function(opt_title)
    {
        return InjectedScriptHost.callFunction(inspectedWindow.console.profileEnd, inspectedWindow.console, slice(arguments));
    },

    /**
     * @param {!Object} object
     * @param {!Array.<string>|string=} opt_types
     */
    monitorEvents: function(object, opt_types)
    {
        if (!object || !object.addEventListener || !object.removeEventListener)
            return;
        var types = this._normalizeEventTypes(opt_types);
        for (var i = 0; i < types.length; ++i) {
            object.removeEventListener(types[i], this._logEvent, false);
            object.addEventListener(types[i], this._logEvent, false);
        }
    },

    /**
     * @param {!Object} object
     * @param {!Array.<string>|string=} opt_types
     */
    unmonitorEvents: function(object, opt_types)
    {
        if (!object || !object.addEventListener || !object.removeEventListener)
            return;
        var types = this._normalizeEventTypes(opt_types);
        for (var i = 0; i < types.length; ++i)
            object.removeEventListener(types[i], this._logEvent, false);
    },

    /**
     * @param {*} object
     * @return {*}
     */
    inspect: function(object)
    {
        return injectedScript._inspect(object);
    },

    copy: function(object)
    {
        var string;
        if (injectedScript._subtype(object) === "node") {
            string = object.outerHTML;
        } else if (injectedScript.isPrimitiveValue(object)) {
            string = toString(object);
        } else {
            try {
                string = JSON.stringify(object, null, "  ");
            } catch (e) {
                string = toString(object);
            }
        }

        var hints = { copyToClipboard: true, __proto__: null };
        var remoteObject = injectedScript._wrapObject(string, "")
        InjectedScriptHost.inspect(remoteObject, hints);
    },

    clear: function()
    {
        InjectedScriptHost.clearConsoleMessages();
    },

    /**
     * @param {!Node} node
     * @return {!Array.<!{type: string, listener: function(), useCapture: boolean, remove: function()}>|undefined}
     */
    getEventListeners: function(node)
    {
        var result = nullifyObjectProto(InjectedScriptHost.getEventListeners(node));
        if (!result)
            return result;
        /** @this {{type: string, listener: function(), useCapture: boolean}} */
        var removeFunc = function()
        {
            node.removeEventListener(this.type, this.listener, this.useCapture);
        }
        for (var type in result) {
            var listeners = result[type];
            for (var i = 0, listener; listener = listeners[i]; ++i) {
                listener["type"] = type;
                listener["remove"] = removeFunc;
            }
        }
        return result;
    },

    debug: function(fn)
    {
        InjectedScriptHost.debugFunction(fn);
    },

    undebug: function(fn)
    {
        InjectedScriptHost.undebugFunction(fn);
    },

    monitor: function(fn)
    {
        InjectedScriptHost.monitorFunction(fn);
    },

    unmonitor: function(fn)
    {
        InjectedScriptHost.unmonitorFunction(fn);
    },

    table: function(data, opt_columns)
    {
        InjectedScriptHost.callFunction(inspectedWindow.console.table, inspectedWindow.console, slice(arguments));
    },

    /**
     * @param {number} num
     */
    _inspectedObject: function(num)
    {
        return InjectedScriptHost.inspectedObject(num);
    },

    /**
     * @param {!Array.<string>|string=} types
     * @return {!Array.<string>}
     */
    _normalizeEventTypes: function(types)
    {
        if (typeof types === "undefined")
            types = ["mouse", "key", "touch", "control", "load", "unload", "abort", "error", "select", "input", "change", "submit", "reset", "focus", "blur", "resize", "scroll", "search", "devicemotion", "deviceorientation"];
        else if (typeof types === "string")
            types = [types];

        var result = [];
        for (var i = 0; i < types.length; ++i) {
            if (types[i] === "mouse")
                push(result, "mousedown", "mouseup", "click", "dblclick", "mousemove", "mouseover", "mouseout", "mousewheel");
            else if (types[i] === "key")
                push(result, "keydown", "keyup", "keypress", "textInput");
            else if (types[i] === "touch")
                push(result, "touchstart", "touchmove", "touchend", "touchcancel");
            else if (types[i] === "control")
                push(result, "resize", "scroll", "zoom", "focus", "blur", "select", "input", "change", "submit", "reset");
            else
                push(result, types[i]);
        }
        return result;
    },

    /**
     * @param {!Event} event
     */
    _logEvent: function(event)
    {
        inspectedWindow.console.log(event.type, event);
    }
}

확인 bound(selector, startNode)하려면 활성화 된 링크를 누르세요.

여기에 이미지 설명 입력

여기에 이미지 설명 입력


콘솔 전용 내장 기능입니다.

https://developer.chrome.com/devtools/docs/commandline-api

참조 URL : https://stackoverflow.com/questions/32240916/already-defined-in-chrome

반응형