摘自:https://developer.chrome.com/docs/devtools/console/utilities/


The Console Utilities API contains a collection of convenience functions for performing common tasks: selecting and inspecting DOM elements, displaying data in readable format, stopping and starting the profiler, and monitoring DOM events.

Warning

Warning: These functions only work when you call them from the Chrome DevTools Console. They won't work if you try to call them in your scripts.

Looking for console.log(), console.error(), and the rest of the console.* functions? See Console API Reference.

#$_

$_ returns the value of the most recently evaluated expression.

In the following example, a simple expression (2 + 2) is evaluated. The $_ property is then evaluated, which contains the same value:

In the next example, the evaluated expression initially contains an array of names. Evaluating $_.length to find the length of the array, the value stored in $_ changes to become the latest evaluated expression, 4:

#$0 - $4

The $0, $1, $2, $3 and $4 commands work as a historical reference to the last five DOM elements inspected within the Elements panel or the last five JavaScript heap objects selected in the Profiles panel. $0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.

In the following example, an img element is selected in the Elements panel. In the Console drawer, $0 has been evaluated and displays the same element:

The image below shows a different element selected in the same page. The $0 now refers to newly selected element, while $1 returns the previously selected one:

#$(selector, [startNode])

$(selector) returns the reference to the first DOM element with the specified CSS selector. When called with one argument, this function is an alias for the document.querySelector() function.

The following example returns a reference to the first  element in the document:

Right-click on the returned result and select 'Reveal in Elements Panel' to find it in the DOM, or 'Scroll in to View' to show it on the page.

The following example returns a reference to the currently selected element and displays its src property:

This function also supports a second parameter, startNode, that specifies an 'element' or Node from which to search for elements. The default value of this parameter is document.

The following example returns a reference to the first element after the currently selected Node and displays its src properly:

Note: If you are using a library such as jQuery that uses $, this functionality will be overwritten, and $ will correspond to that library's implementation.

#$$(selector, [startNode])

$$(selector) returns an array of elements that match the given CSS selector. This command is equivalent to calling document.querySelectorAll().

The following example uses $$() to create an array of all  elements in the current document and displays the value of each element's src property:

let images = $$('img');
for (let each of images) {
  console.log(each.src);
}

This function also supports a second parameter, startNode, that specifies an element or Node from which to search for elements. The default value of this parameter is document.

This modified version of the previous example uses $$() to create an array of all  elements that appear in the current document after the selected Node:

let images = $$('img', document.querySelector('.devsite-header-background'));
for (let each of images) {
  console.log(each.src);
}

Note: Press Shift + Enter in the console to start a new line without executing the script.

#$x(path, [startNode])

$x(path) returns an array of DOM elements that match the given XPath expression.

For example, the following returns all the

elements on the page:

$x("//p")

The following example returns all the

elements that contain  elements:

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

Similar to the other selector functions, $x(path) has an optional second parameter, startNode, that specifies an element or Node from which to search for elements.

#clear()

clear() clears the console of its history.

clear();

#copy(object)

copy(object) copies a string representation of the specified object to the clipboard.

copy($0);

#debug(function)

When the specified function is called, the debugger is invoked and breaks inside the function on the Sources panel allowing to step through the code and debug it.

debug(getData);

Use undebug(fn) to stop breaking on the function, or use the UI to disable all breakpoints.

For more information on breakpoints, see Pause Your Code With Breakpoints.

#dir(object)

dir(object) displays an object-style listing of all the specified object's properties. This method is an alias for the Console API's console.dir() method.

The following example shows the difference between evaluating document.body directly in the command line, and using dir() to display the same element:

document.body;
dir(document.body);

For more information, see the console.dir() entry in the Console API.

#dirxml(object)

dirxml(object) prints an XML representation of the specified object, as seen in the Elements tab. This method is equivalent to the console.dirxml() method.

#inspect(object/function)

inspect(object/function) opens and selects the specified element or object in the appropriate panel: either the Elements panel for DOM elements or the Profiles panel for JavaScript heap objects.

The following example opens the document.body in the Elements panel:

inspect(document.body);

When passing a function to inspect, the function opens the document up in the Sources panel for you to inspect.

#getEventListeners(object)

getEventListeners(object) returns the event listeners registered on the specified object. The return value is an object that contains an array for each registered event type (click or keydown, for example). The members of each array are objects that describe the listener registered for each type. For example, the following lists all the event listeners registered on the document object:

getEventListeners(document);

If more than one listener is registered on the specified object, then the array contains a member for each listener. In the following example, there are two event listeners registered on the document element for the click event:

You can further expand each of these objects to explore their properties:

#keys(object)

keys(object) returns an array containing the names of the properties belonging to the specified object. To get the associated values of the same properties, use values().

For example, suppose your application defined the following object:

let player1 = { "name": "Ted", "level": 42 };

Assuming player1 was defined in the global namespace (for simplicity), typing keys(player1) and values(player1) in the console results in the following:

#monitor(function)

When the function specified is called, a message is logged to the console that indicates the function name along with the arguments that are passed to the function when it was called.

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

Use unmonitor(function) to cease monitoring.

#monitorEvents(object[, events])

When one of the specified events occurs on the specified object, the Event object is logged to the console. You can specify a single event to monitor, an array of events, or one of the generic events "types" mapped to a predefined collection of events. See examples below.

The following monitors all resize events on the window object.

monitorEvents(window, "resize");

The following defines an array to monitor both "resize" and "scroll" events on the window object:

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

You can also specify one of the available event "types", strings that map to predefined sets of events. The table below lists the available event types and their associated event mappings:

Event type & Corresponding mapped events

mouse

"mousedown", "mouseup", "click", "dblclick", "mousemove", "mouseover", "mouseout", "mousewheel"

key

"keydown", "keyup", "keypress", "textInput"

touch

"touchstart", "touchmove", "touchend", "touchcancel"

control

"resize", "scroll", "zoom", "focus", "blur", "select", "change", "submit", "reset"

For example, the following uses the "key" event type all corresponding key events on an input text field currently selected in the Elements panel.

monitorEvents($0, "key");

Below is sample output after typing a characters in the text field:

#profile([name]) and profileEnd([name])

profile() starts a JavaScript CPU profiling session with an optional name. profileEnd() completes the profile and displays the results in the Profile panel. (See also Speed Up JavaScript Execution.)

To start profiling:

profile("My profile")

To stop profiling and display the results in the Profiles panel:

profileEnd("My profile")

Profiles can also be nested. For example, this will work in any order:

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

Result in the profiles panel:

Note: Multiple CPU profiles can operate at once and you aren't required to close them out in creation order.

#queryObjects(Constructor)

Call queryObjects(Constructor) from the console to return an array of objects that were created with the specified constructor. For example:

queryObjects(Promise). Returns all instances of Promise.

queryObjects(HTMLElement). Returns all HTML elements.

queryObjects(foo), where foo is a class name. Returns all objects that were instantiated via new foo().

The scope of queryObjects() is the currently-selected execution context in the console.

#table(data[, columns])

Log object data with table formatting by passing in a data object in with optional column headings. For example, to display a list of names using a table in the console, you would do:

let names = [
  { firstName: "John", lastName: "Smith" },
  { firstName: "Jane", lastName: "Doe" },
];
table(names);

#undebug(function)

undebug(function) stops the debugging of the specified function so that when the function is called, the debugger is no longer invoked. This is used in concert with debug(fn).

undebug(getData);

#unmonitor(function)

unmonitor(function) stops the monitoring of the specified function. This is used in concert with monitor(fn).

unmonitor(getData);

#unmonitorEvents(object[, events])

unmonitorEvents(object[, events]) stops monitoring events for the specified object and events. For example, the following stops all event monitoring on the window object:

unmonitorEvents(window);

You can also selectively stop monitoring specific events on an object. For example, the following code starts monitoring all mouse events on the currently selected element, and then stops monitoring "mousemove" events (perhaps to reduce noise in the console output):

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

#values(object)

values(object) returns an array containing the values of all properties belonging to the specified object.

values(object);

Last updated: Monday, August 16, 2021 Improve article

Console Utilities API reference相关推荐

  1. wsgiref — WSGI Utilities and Reference Implementation¶

    20.4. wsgiref - WSGI Utilities and Reference Implementation - Python v2.7.3 documentation wsgiref - ...

  2. 【NFC】Android NFC API Reference中英文

    SkySeraph 博客园 首页 新随笔 联系 订阅 管理 随笔- 192  文章- 0  评论- 441  [NFC]Android NFC API Reference中英文 [NFC]Androi ...

  3. Skia Overview and API Reference

    Skia简介和图形案例 Overview Skia是一个开源的2D图形库,提供各种常用的API,并可在多种软硬件平台上运行.谷歌Chrome浏览器.Chrome OS.Android.火狐浏览器.火狐 ...

  4. .net api reference中文_在macOS上使用.NET SDK编译 .NET 通用中间语言

    当你编译C#.F#或http://VB.NET代码时,编译器不会将其编译成原生代码,而是将其编译成通用中间语言.然后,IL代码被CLR/CoreCLR编译成可以在CPU上运行的机器代码.我想给大家展示 ...

  5. 在线html5 api中文版,HTML5+ API Reference

    IO模块管理本地文件系统,用于对文件系统的目录浏览.文件的读取.文件的写入等操作.通过plus.io可获取文件系统管理对象. 常量: 方法: 对象: DirectoryEntry: 文件系统中的目录对 ...

  6. html5在线api,HTML5+ API Reference

    Push模块管理推送消息功能,可以实现在线.离线的消息推送,通过plus.push可获取推送消息管理对象. 方法: 对象: ClientInfo: JSON对象,获取的客户端标识信息 PushMess ...

  7. Windows API Reference for C#, VB.NET

    不错的.net 下用API的参考站点 地址在:http://www.webtropy.com/articles/Win32-API-DllImport-art9.asp 下面摘抄分类,便于大家直接就拿 ...

  8. kmdjs api reference

    总览 kmdjs的主要就两个API:kmdjs.config和define kmdjs.config kmdjs.config是用于项目整体配置,一般的配置如下所示: kmdjs.config({na ...

  9. SAP WebIDE:how to enable context API reference

    Created by Wang, Jerry on Jan 18, 2015 complete url: https://sapui5.hana.ondemand.com/sdk/#docs/api/ ...

最新文章

  1. 基于 eBPF 的新型追踪工具:bpftrace
  2. C++基础-string截取、替换、查找子串函数
  3. 2字节取值范围_5G NR 下行同步SSB(2)—PSS和SSS的用途
  4. word List 17
  5. 【JavaWeb】前端框架之Bootstrap
  6. Tree Context Menu
  7. You are here: Prof Andrew Binley's Homepage R3t
  8. java jdk下载_jdk1.7下载|Java Development Kit (JDK) 下载「64位」-太平洋下载中心
  9. python开发android应用app,python开发app开发框架
  10. CEH v7 培训视频、工具、PPT
  11. 用python开发手机游戏_python开发安卓app
  12. 出售主题HTML代码,房地产HTML主题
  13. Elasticsearch 运行时类型 Runtime fields 深入详解
  14. OA系统-员工的添加和查询-登录功能的实现
  15. 串口拓展测试方法及步骤--信而泰TeleATT测试软件实操
  16. 抽样技术---分层随机抽样
  17. 《工程测量学》考试复习总结
  18. 新华三网络部署(和思科的区别)
  19. wbin about
  20. 华为VPLS配置案例S6720

热门文章

  1. PIC16F1829 单片机配置和DEMO CODE
  2. 设计师怎样学习网站开发
  3. 虚拟人火了,你准备好了吗?
  4. AT2382-[AGC015D]A or...or B Problem
  5. Python工作日类库Busines Holiday介绍
  6. 带参数的线性方程组怎么用计算机解,带参数的线性方程组的解法.docx
  7. web移动开发技能图谱以及注意事项
  8. surfer编辑color scale ,坐标投影后添加经纬度线
  9. 如何使用google提高搜索效率
  10. ROS遇到问题:rosdep找不到