控制台实用工具 API 参考Console Utilities API reference

控制台实用程序 API 包含一组方便命令,用于完成以下常见任务。The Console Utilities API contains a collection of convenience commands to complete the following common tasks.

  • 选择并检查 DOM 元素Choose and inspect DOM elements
  • 以可读格式显示数据Display data in readable format
  • 停止并启动探查器Stop and start the profiler
  • 监视 DOM 事件Monitor DOM events

警告

以下命令仅适用于开发人员Microsoft Edge控制台The following commands only work in the Microsoft Edge DevTools Console. 如果从脚本运行,则命令不起作用。The commands do not work if run from your scripts.

有关 和 方法以及方法其余部分的信息, console.log() console.error() console.* 请导航到"控制台 API参考"。For more information about the console.log() and console.error() methods and the rest of the console.* methods, navigate to Console API Reference.

最近计算表达式Recently evaluated expression

控制台语法Console syntax

$_

此命令返回最近计算表达式的值。This command returns the value of the most recently evaluated expression.

控制台示例Console example

在下图中,将计算一个简单的表达式 \ (2 + 2 ) 。In the following figure, a simple expression (2 + 2) is evaluated. 然后 $_ 计算属性,其中包含相同的值。The $_ property is then evaluated, which contains the same value.

$_ 是最近评估的表达式

在下图中,计算表达式最初包含一个名称数组。In the following figure, the evaluated expression initially contains an array of names. 计算 以查找数组的长度,存储在 中的值 $_.length $_ 将成为最新的计算表达式 4Evaluating $_.length to find the length of the array, the value stored in $_ becomes the latest evaluated expression, 4.

$_ 评估新命令时的更改


最近选择的元素或 JavaScript 对象Recently chosen element or JavaScript object

控制台语法Console syntax

$0

此命令返回最近选择的元素或 JavaScript 对象。This command returns the most recently chosen element or JavaScript object. $1 返回第二个最近选择一个,等等。returns the second most recently chosen one, and so on. 、 、 和 命令用作对在元素工具中检查的最后 $0 $1 $2 $3 $4 五个 DOM******** 元素或内存工具中选定的最后五个 JavaScript 堆对象的历史引用。The $0, $1, $2, $3, and $4 commands work as a historical reference to the last five DOM elements inspected within the Elements tool or the last five JavaScript heap objects chosen in the Memory tool.

$0
$1
$2
$3
$4

 

控制台示例Console example

在下图中, img 在"元素"工具中选择了 一个元素In the following figure, an img element is chosen in the Elements tool. 控制台箱$0 ,已进行评估并显示相同的元素。In the Console drawer, $0 has been evaluated and displays the same element.

$0

下图中,图像显示在同一网页中选择的不同元素。In the following figure, the image displays a different element chosen in the same webpage. $0现在引用新选择的元素,而 $1 返回之前选择的元素。The $0 now refers to the newly chosen element, while $1 returns the previously chosen one.

$1


查询选择器Query selector

控制台语法Console syntax

$(selector, [startNode])

此命令返回对具有指定 CSS 选择器的第一个 DOM 元素的引用。This command returns the reference to the first DOM element with the specified CSS selector. 此方法是 document.querySelector () 别名。This method is an alias for the document.querySelector() method.

控制台示例Console example

在下图中,将返回对网页 <img> 中第一个元素的引用。In the following figure, a reference to the first <img> element in the webpage is returned.

$ ('img')

若要在 DOM 中查找第一个元素或在网页上查找并显示该元素,请完成以下操作。To find the first element in the DOM or to find and display it on the webpage, complete the following actions.

  1. 将鼠标悬停在返回的结果上。Hover on the returned result.
  2. 打开上下文菜单\(右键单击\)。Open the contextual menu (right-click).
  3. 选择 "元素面板"中的"展示"。Choose Reveal in Elements Panel.

在下图中,将返回对当前选择的元素的引用, src 并显示 属性。In the following figure, a reference to the currently chosen element is returned and the src property is displayed.

$ ('img') .src

此方法还支持第二个参数 ,用于指定要搜索的元素或 startNode 节点。This method also supports a second parameter, startNode, that specifies an element or node from which to search for elements. 参数的默认值为 documentThe default value of the parameter is document.

在下图中,找到 img 元素后的第一个元素 title--image ,并返回 src img 元素的 属性。In the following figure, the first img element after the title--image element is found, and the src property of the img element is returned.

$ ('img', document.querySelector ('title--image') ) .src

备注

如果使用的库(如 jQuery)使用 ,则功能将被覆盖,并且对应于该库中 $ $ 的实现。If you are using a library such as jQuery that uses $, the functionality is overwritten, and $ corresponds to the implementation from that library.


查询选择器全部Query selector all

控制台语法Console syntax

$$(selector, [startNode])

此命令返回匹配指定 CSS 选择器的元素数组。This command returns an array of elements that match the specified CSS selector. 此方法等效于运行 document.querySelectorAll () 方法。This method is equivalent to running the document.querySelectorAll() method.

控制台示例Console example

在下面的代码示例和图中,使用 创建当前网页中所有元素的数组 $$() <img> 并显示每个 src 元素的 属性值。In the following code sample and figure, use $$() to create an array of all <img> elements in the current webpage and display the value of the src property for each element.

var images = $$('img');
for (each in images) {
    console.log(images[each].src);
}

使用 $$ () 选择网页中的所有图像并显示源

此方法还支持第二个参数 ,用于指定要搜索的元素或 startNode 节点。This method also supports a second parameter, startNode, that specifies an element or node from which to search for elements. 参数的默认值为 documentThe default value of the parameter is document.

在下面的代码示例和图中,上一个代码示例和图的修改版本用于创建一个数组,该数组包含当前网页中所选节点之后 $$() <img> 出现的所有元素。In the following code sample and figure, a modified version of the previous code sample and figure uses $$() to create an array of all <img> elements that appear in the current webpage after the chosen node.

var images = $$('img', document.querySelector(`title--image`));
for (each in images) {
   console.log(images[each].src);
}

使用 $$ () 选择在网页中的指定 div <div>后显示的所有图像并显示源

备注

Shift + Enter 控制台中选择以在不运行脚本的情况下启动新行。Select Shift+Enter in the Console to start a new line without running the script.


XPathXPath

控制台语法Console syntax

$x(path, [startNode])

此命令返回匹配指定 XPath 表达式的 DOM 元素的数组。This command returns an array of DOM elements that match the specified XPath expression.

控制台示例Console example

在下面的代码示例和图中,将返回 <p> 网页上的所有元素。In the following code sample and figure, all of the <p> elements on the webpage are returned.

$x("//p")

使用 XPath 选择器

在下面的代码示例和图中,将返回 <p> 包含元素 <a> 的所有元素。In the following code sample and figure, all of the <p> elements that contain <a> elements are returned.

$x("//p[a]")

使用更复杂的 XPath 选择器

与其他选择器命令类似,具有可选的第二个参数 ,用于指定要搜索的元素或 $x(path) startNode 节点。Similar to the other selector commands, $x(path) has an optional second parameter, startNode, that specifies an element or node from which to search for elements.

将 XPath 选择器与 startNode 一同使用


clearclear

控制台语法Console syntax

clear()

此命令清除历史记录的控制台。This commnad clears the console of the history.

控制台示例Console example

clear()

copycopy

控制台语法Console syntax

copy(object)

此方法将指定对象的字符串表示形式复制到剪贴板。This method copies a string representation of the specified object to the clipboard.

控制台示例Console example

copy($0)

调试debug

控制台语法Console syntax

debug(method)

备注

Chromium跟踪#1050237 Bug 时出现 debug() 的问题。The Chromium issue #1050237 is tracking a bug with the debug() function. 如果遇到问题,请尝试改为 使用断 点。If you encounter the issue, try using breakpoints instead.

请求指定方法时,调试程序在 Sources 工具的 方法内调用和中断。When you request the specified method, the debugger invokes and breaks inside the method on the Sources tool. 它允许你逐步调试代码。It allows you to step through and debug the code.

控制台示例Console example

debug("debug");

使用调试工具在方法 ()

用于 undebug(method) 停止方法上的中断,或使用 UI 关闭所有断点。Use undebug(method) to stop breaking on the method, or use the UI to turn off all breakpoints.

有关断点详细信息,请导航到如何在DevTools中暂停包含断Microsoft Edge代码。For more information on breakpoints, navigate to How to pause your code with breakpoints in Microsoft Edge DevTools.


dirdir

控制台语法Console syntax

dir(object)

此命令显示指定对象的所有属性的对象样式列表。This command displays an object-style listing of all of the properties for the specified object. 此方法是 console.dir () 别名。This method is an alias for the console.dir() method.

document.head 控制台 中进行评估 ,以显示 和 标记 <head> 之间的 </head> HTML。Evaluate document.head in the Console to display the HTML between the <head> and </head> tags.

控制台示例Console example

在下面的代码示例和图中,在控制台 中使用 后将显示对象 console.dir() 样式 列表In the following code sample and figure, an object-style listing is displayed after using console.dir() in the Console.

document.head;
dir(document.head);

使用 dir 方法记录 document.head () 方法

有关详细信息,请导航到控制台 API中的 console.dir () 。For more information, navigate to console.dir() in the Console API.


dirxmldirxml

控制台语法Console syntax

dirxml(object)

此命令打印指定对象的 XML 表示形式,如 元素 工具中显示。This command prints an XML representation of the specified object, as displayed in the Elements tool. 此方法等效于 console.dirxml () 方法。This method is equivalent to the console.dirxml() method.


inspectinspect

控制台语法Console syntax

inspect(object/method)

此命令将在适当的面板中打开并选择指定的元素或对象:DOM 元素的 Elements 工具或 JavaScript 堆对象的 Memory 工具。This command opens and chooses the specified element or object in the appropriate panel: either the Elements tool for DOM elements or the Memory tool for JavaScript heap objects.

控制台示例Console example

在下面的代码示例和图中,将在 document.body "元素"工具 打开 。In the following code sample and figure, the document.body opens in the Elements tool.

控制台示例Console example

inspect(document.body);

检查元素并检查 ()

传递要检查的方法时,该方法将在 " 源"工具中打开网页供你检查。When passing a method to inspect, the method opens the webpage in the Sources tool for you to inspect.


getEventListenersgetEventListeners

控制台语法Console syntax

getEventListeners(object)

此命令返回在指定对象上注册的事件侦听器。This command returns the event listeners registered on the specified object. 返回值是包含每个已注册事件类型 \ ((如 或 click keydown ) )的数组的对象。The return value is an object that contains an array for each registered event type (such as click or keydown). 每个数组的成员是描述为每种类型注册的侦听器的对象。The members of each array are objects that describe the listener registered for each type.

控制台示例Console example

下面的代码段和图列出了在 对象上注册的所有事件 document 侦听器。In the following code snippet and figure, all of the event listeners registered on the document object are listed.

getEventListeners(document);

使用 getEventListeners 文档库 (输出)

如果指定对象上注册了多个侦听器,则数组将包含每个侦听器的成员。If more than one listener is registered on the specified object, then the array contains a member for each listener. 下图中,在 事件的 元素上注册了两 documentclick 事件侦听器。In the following figure, two event listeners are registered on the document element for the click event.

多个侦听器

可以进一步展开以下每个对象来浏览属性。You may further expand each of the following objects to explore the properties.

侦听器对象的扩展视图


keys

控制台语法Console syntax

keys(object)

此命令返回一个数组,其中包含属于指定对象的属性的名称。This command returns an array containing the names of the properties belonging to the specified object. 若要获取相同属性的关联值,请使用 values()To get the associated values of the same properties, use values().

控制台示例Console example

例如,假设应用程序定义了以下对象。For example, suppose your application defined the following object.

var player1 = {"name": "Ted", "level": 42}

在下面的代码示例和图中,为了简单起见,在键入和在控制台中) 在全局命名空间 \ (中定义了 player1 keys(player1) values(player1) 结果假定。In the following code samples and figure, the result assumes player1 was defined in the global namespace (for simplicity) before you type keys(player1) and values(player1) in the console.

keys(player1)

values(player1)

键 () 和值 () 命令


监视器monitor

控制台语法Console syntax

monitor(method)

此命令向控制台记录一条消息,指示方法名称以及作为请求的一部分传递给方法的参数。This command logs a message to the console that indicates the method name along with the arguments passed to the method as part of a request.

控制台示例Console example

function sum(x, y) {
    return x + y;
}
monitor(sum);

监视器 () 方法

用于 unmonitor(method) 结束监视。Use unmonitor(method) to end monitoring.


monitorEventsmonitorEvents

控制台语法Console syntax

monitorEvents(object[, events])

当指定对象上发生指定事件之一时,该事件对象将记录到控制台。When one of the specified events occurs on the specified object, the event object is logged to the console. 可以指定要监视的单个事件、事件数组或映射到预定义的事件集合的泛型事件类型之一。You may specify a single event to monitor, an array of events, or one of the generic events types that are mapped to a predefined collection of events.

控制台示例Console example

查看以下代码示例和图。Review the following code sample and figure.

下面监视 window 对象上的所有调整大小事件。The following monitors all resize events on the window object.

monitorEvents(window, "resize");

监视窗口大小事件

以下代码段定义一个数组,用于监视窗口对象上的 和 resize scroll 事件。The following code snippet defines an array to monitor both resize and scroll events on the window object.

monitorEvents(window, ["resize", "scroll"]);

还可以指定一种可用的事件类型,即映射到预定义的事件集的字符串。You may also specify one of the available types of events, strings that map to predefined sets of events. 下表显示可用的事件类型和关联的事件映射。The following table displays the available event types and the associated event mappings.

事件类型Event type 相应的映射事件Corresponding mapped events
mouse "click"、"dblclick"、"mousedown"、"mousemove"、"mouseout"、"mouseover"、"mouseup"、"mousewheel""click", "dblclick", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "mousewheel"
key "keydown"、"keypress"、"keyup"、"textInput""keydown", "keypress", "keyup", "textInput"
touch "touchcancel"、"touchend"、"touchmove"、"touchstart""touchcancel", "touchend", "touchmove", "touchstart"
control "blur"、"change"、"focus"、"reset"、"resize"、"scroll"、"select"、"submit"、"zoom""blur", "change", "focus", "reset", "resize", "scroll", "select", "submit", "zoom"

在下面的代码示例中,当前在 Elements 工具中选择了与输入文本字段上的事件 key key 对应的 事件 类型。In the following code sample, the key event type corresponding to key events on an input text field are currently chosen in the Elements tool.

monitorEvents($0, "key");

下图显示了在文本字段中键入字符后的示例输出。In the following figure, the sample output after typing a character in the text field is displayed.

监视关键事件


profileprofile

控制台语法Console syntax

profile([name])

此命令使用可选名称启动 JavaScript CPU 分析会话。This command starts a JavaScript CPU profiling session with an optional name. profileEnd () 方法完成配置文件,并显示内存工具的结果。The profileEnd() method completes the profile and displays the results in the Memory tool.

控制台示例Console example

  1. 运行 profile() 方法以开始分析。Run the profile() method to start profiling.

    profile("My profile")
    
  2. 运行 profileEnd () 方法停止分析和在内存工具 中显示 结果。Run the profileEnd() method to stop profiling and display the results in the Memory tool.

配置文件也可以嵌套。Profiles may also be nested. 在下面的代码示例和图中,无论顺序如何,结果都是相同的。In the following code samples and figure, the result is the same whatever the order.

profile('A');
profile('B');
profileEnd('A');
profileEnd('B');

备注

多个 CPU 配置文件可以同时运行,并且不需要按照创建顺序关闭每个配置文件。Multiple CPU profiles may operate at the same time and you are not required to close-out each one in creation order.


profileEndprofileEnd

控制台语法Console syntax

profileEnd([name])

此命令完成 JavaScript CPU 分析会话,并显示内存工具 的结果。This command completes a JavaScript CPU profiling session and displays the results in the Memory tool. 必须运行配置文件 () 方法。You must be running the profile() method.

控制台示例Console example

  1. 运行 配置文件 () 方法开始分析。Run the profile() method to start profiling.

  2. 运行 profileEnd() 方法以停止分析,在内存工具中 显示 结果。Run the profileEnd() method to stop profiling and display the results in the Memory tool.

    profileEnd("My profile")
    

配置文件也可以嵌套。Profiles may also be nested. 在下面的代码示例和图中,无论顺序如何,结果都是相同的。In the following code sample and figure, the result is the same whatever the order.

profile('A');
profile('B');
profileEnd('A');
profileEnd('B');

结果在内存工具中显示为堆 快照The result appears as a Heap Snapshot in the Memory tool.

分组配置文件

备注

多个 CPU 配置文件可以同时运行,并且不需要按照创建顺序关闭每个配置文件。Multiple CPU profiles may operate at the same time and you are not required to close-out each one in creation order.


queryObjectsqueryObjects

控制台语法Console syntax

queryObjects(Constructor)

此命令返回使用指定构造函数创建的对象数组。This command returns an array of objects created with the specified constructor. 的范围 queryObjects() 是控制台 中当前选择的运行时 上下文The scope of queryObjects() is the currently chosen runtime context in the Console.

控制台示例Console example

queryObjects(promise)

返回所有 PromisesReturns all Promises.

queryObjects(HTMLElement)

返回所有 HTML 元素。Returns all HTML elements.

queryObjects(functionName)

返回使用 实例化的所有对象 new functionName()Returns all objects that were instantiated using new functionName().


tabletable

控制台语法Console syntax

table(data[, columns])

此命令根据数据对象(列标题为可选)使用表格式记录对象数据。This command logs object data with table formatting based upon the data object in with optional column headings.

控制台示例Console example

下面的代码示例和图显示了使用控制台中的表的名称列表。In the following code sample and figure, a list of names using a table in the console is displayed.

var names = {
    0:  {
        firstName:  "John",
        lastName:  "Smith"
    },
    1:  {
        firstName:  "Jane",
        lastName:  "Doe"
    }
};
table(names);

table 方法 () 结果


undebugundebug

控制台语法Console syntax

undebug(method)

此命令停止对指定方法的调试。This command stops the debug of the specified method. 因此,当请求该方法时,将不再调用调试器。So when the method is requested, the debugger is no longer invoked.

控制台示例Console example

undebug(getData);

unmonitorunmonitor

控制台语法Console syntax

unmonitor(method)

此命令停止对指定方法的监视。This command stops the monitoring of the specified method. 此方法与监视器和 () 一起 使用。This method is used in concert with the monitor() method.

控制台示例Console example

unmonitor(getData);

unmonitorEventsunmonitorEvents

控制台语法Console syntax

unmonitorEvents(object[, events])

此命令停止监视指定对象和事件的事件。This command stops monitoring events for the specified object and events.

控制台示例Console example

例如,以下代码段停止窗口对象上的所有事件监视。For example, the following code snippet stops all event monitoring on the window object.

unmonitorEvents(window);

还可以有选择地停止监视对象上的特定事件。You may also selectively stop monitoring specific events on an object. 例如,以下代码开始监视当前选择的元素上的所有事件,然后停止监视 mouse mousemove 事件 \ (也许以减少控制台输出) 。For example, the following code starts monitoring all mouse events on the currently chosen element, and then stops monitoring mousemove events (perhaps to reduce noise in the console output).

monitorEvents($0, "mouse");
unmonitorEvents($0, "mousemove");

valuesvalues

控制台语法Console syntax

values(object)

此命令返回一个数组,其中包含属于指定对象的所有属性的值。This command returns an array containing the values of all properties belonging to the specified object.

控制台示例Console example

values(object);

联系 Microsoft Edge DevTools 团队Getting in touch with the Microsoft Edge DevTools team

使用以下选项讨论帖子中的新功能和更改,或与 DevTools 相关的任何其他内容。Use the following options to discuss the new features and changes in the post, or anything else related to DevTools.

  • 使用“发送反馈”图标发送反馈,或在 DevTools 中选择Alt+Shift+I \ (Windows、Linux) 或 Option+Shift+I \ (macOS)。Send your feedback using the Send Feedback icon or select Alt+Shift+I (Windows, Linux) or Option+Shift+I (macOS) in DevTools.
  • 发推 @EdgeDevToolsTweet at @EdgeDevTools.
  • 我们想要的 Web 提交建议。Submit a suggestion to The Web We Want.
  • 若要提交有关本文的错误,请使用以下“反馈” 部分。To file bugs about this article, use the following Feedback section.

Microsoft Edge DevTools 中的“发送反馈”图标

备注

此页面的某些部分是根据 Google 创建和共享的作品所做的修改,并根据 Creative Commons Attribution 4.0 International License 中描述的条款使用。Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons Attribution 4.0 International License.
原始页面位于此处,由 Kayce Basques\(Chrome DevTools & Lighthouse 的技术作家\)撰写。The original page is found here and is authored by Kayce Basques (Technical Writer, Chrome DevTools & Lighthouse).

Creative Commons License
本作品根据 Creative Commons Attribution 4.0 International License 获得许可。This work is licensed under a Creative Commons Attribution 4.0 International License.