Reprinted: incomplete guide to the chrome Console

Source: Internet
Author: User
Tags chrome developer chrome developer tools chrome devtools

Chrome's developer tools have been powerful to the point of no friends, especially the console with rich functions and friendly interfaces. when used properly, they can have the following functions:

  • Higher "Force Grid" faster "Development debugging" more "Class-oriented frontend 」
  • The bug is everywhere. "console is great 」
Console. Log

Everyone will use log, but some people use it very well.console.error,console.warn.
They have little difference in functionality, meaning that they classify the information output to the console, or make them more semantic.
The semantics of each parameter is as follows:

  • console.log: Common Information
  • console.info: Prompt class information
  • console.error: Error message
  • console.warn: Warning Information

After using the preceding log method properly, you can easily select a specific type of information on the console.

Console. Log ('one red heart to the sun', 'Roar ~ '); Console.info ('the upstairs medicine cannot be stopped! '); Console. Warn (' Upstairs mouth is too cheap! '); Console. Error ('the upstairs is the case for you? ');

If you try againconsole.groupAndconsole.groupEndCan bring this classification management idea to the extreme. This is suitable for grouping log information into groups named by their namespaces when developing a large-sized web app with many complicated modules.

Console. group ("app. foo "); console. log ("information from the foo module... "); console. groupend (); console. group ("app. bar "); console. log ("information from the bar module... "); console. groupend ();

And aboutconsole.logAnd has been played badly. Everything comes from Chrome's provision of such an API: the first parameter can contain some formatted commands such%c.

For examplehello worldMake a beautiful wedding dress and pull it out again:

console.log(‘%chello world‘,‘font-size:25px;color:red;‘);

If you don't think it is good enough, apply the most gorgeous CSS style you can write, such as gradient. So you can get the following gorgeous results:

console.log(‘%chello world‘, ‘background-image:-webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );color:transparent;-webkit-background-clip: text;font-size:5em;‘);

The pace of various moves ~

You don't need to worry about the intensive code above.console.log()The second parameter is purely CSS used to control the style. The first parameter can contain escape commands starting with a percent sign, such as%cCommand. For more instructions, see the table in the official API documentation.

If it is not enough, let's log some pictures, or even... Animation?
Yes, you must first have a picture. Let's take this picture as an example.

console.log("%c", "padding:50px 300px;line-height:120px;background:url(‘http://wayou.github.io/2014/09/10/chrome-console-tips-and-tricks/rabbit.gif‘) no-repeat;");

Look at the above swing bean than rabbit is not a kind of smoke it face impulse.

In addition,console.tableThe data is output directly in the form of a table, which cannot be liked too much!
Use the example in a previous blog post:

VaR DATA = [{'item name': 'dures', 'quantity ': 4}, {'item name': 'okamoto', 'quantity ': 3}]; console. table (data );

In addition,console.log()Parameters are not fixed. They are separated by commas (,). The output will connect them with blank characters.

Console. Log ('% C ', 'color: red; ', 'xiaoming', 'Do you know that Xiaohong was hit by mom ');

Console. Assert

When you want to output information to the console only when the Code meets certain conditions, you do not have to writeifOr a ternary expression to achieve the goal,cosole.assertThis is a good tool in this scenario. It will first assert the input expression and output the corresponding information to the console only when the expression is false.

VaR isdebug = false; console. Assert (isdebug, 'Log information in development... ');

Console. Count

In addition to conditional output, count is also a common scenario.
When you want to count how many times a piece of code has been executed, you do not have to write the relevant logic on your own. The built-inconsole.countCan be competent for such a task.

Function Foo () {// other function logic blah... Console. Count ('foo execution times: ');} Foo ();

Console. dir

Output the DOM node as a JavaScript Object to the console
Whileconsole.logIs to directly output the DOM node in the structure of the DOM tree, which is consistent with the structure seen during element review. Different forms of presentation, the same elegance, the choice of various positions is convenient and considerate.

console.dir(document.body);console.log(document.body);

Console. Time & console. timeend

Some debugging information is the most common function in the console. Of course, its function is far more than that. For some performance tests, it is also convenient here.
For example, you can useconsole.timeAndconsole.timeEndDo this.

Here is an example from the official document:

console.time("Array initialize");var array= new Array(1000000);for (var i = array.length - 1; i >= 0; i--) {    array[i] = new Object();};console.timeEnd("Array initialize");

Of course, you can also choose to write your own code for timing:

var start=new Date().getTime();var array= new Array(1000000);for (var i = array.length - 1; i >= 0; i--) {    array[i] = new Object();};console.log(new Date().getTime()-start);

I believe you can see that the built-inconsole.timeHow convenient it is, saving the workload of writing code by yourself. It is also worth mentioning that by calling the built-inconsole.timeThe result is more accurate and reliable than the time difference calculated manually.

Console. Profile & console. timelime

You can useconsole.profileCooperationconsole.profileEndTo fulfill this requirement.
This function can be completed through the UI. A tab in the chrome developer tool isProfile.

Similar features includeconsole.timeLineCooperationconsole.timeLineEndIt starts to record a timeline. It can also be used in chrome Developer ToolsTimelineLabel.

So in my opinion, these two methods are a little tricky, because they can be completed through the operation interface. But at least he provides a command line interaction mode, but he still has another posture for choice.

Console. Trace

Stack tracing-related debugging can be usedconsole.trace. This can also be done through the UI. After the code is brokenCall StackView related stack information in the panel.

All of the above are hangingwindow.consoleThe methods under this object are collectively referred to as console APIs. The following methods should be called commands exactly. They are provided in chrome and used in the console. They are collectively called command line APIs.

$

It seems that USD is always favored by programmers and various programming languages. "You can see the PHP code to know how much phper loves money." In the chrome console, $ is quite useful and convenient.
$_The command returns the result of the last expression execution. The function is the same as pressing the up arrow key and then press enter, but it can be used as a variable in your next expression:

2 + 2 // press enter, and then $ _ + 1 // press enter to get 5

The above$_You need to understand its meaning to use it properly, and $0 ~ $4 indicates the last five DOM nodes you have selected.
What does it mean? Right-click on the page and selectReview ElementsAnd then click on the pop-up Dom node tree. These vertices will be recorded, and$0The latest Dom node is returned, and so on. $1 returns the DOM Node Selected last time. Up to five DOM nodes are saved. If not five DOM nodes are returned.undefined.

In addition, the chrome console supports jquery-Like native selectors, that is, you can use$Add a familiar CSS selector to select DOM nodes.

$(‘body‘)

$ (Selector) returns the First Dom element that meets the selection criteria.
Stripped her hypocritical coat, in fact$(selector)Is native Javascriptdocument.querySelector().
At the same time, another command$$(selector)The returned result is a set of all elements that meet the selection criteria.document.querySelectorAll().

$$(‘div‘)

Copy

You can use this command to copy the content obtained on the console to the clipboard.

copy(document.body)

Then you can stick it everywhere:

After reading this command line, did you come up with the idea that you are just as clever as I am: that is, you can use this command to copy in Javascript without relying on the flash plug-in.
But the reality is cruel. As described earlier, the console commands can only be executed in the Console environment, because they are not attached to any global variables suchwindowIn fact, this cannot be accessed in the JS Code.copySo it is impossible to call the copy function at the code level. I hope that some browsers will provide corresponding JS implementations ~

Keys & values

This is a pair of friends. The former returns data composed of all attribute names of the input object, and the latter returns an array composed of all attribute values. For details, see the following example:

var tboy={name:‘wayou‘,gender:‘unknown‘,hobby:‘opposite to the gender‘};keys(tboy);values(tboy);

Monitor & unmonitor

Monitor (function), which receives a function name as a parameter, suchfunction a, Each timeaIf executed, a message will be output on the console, which contains the function name.aAnd the parameters passed in during execution.

The unmonitor (function) is used to stop this listener.

function sayHello(name){alert(‘hello,‘+name);}monitor(sayHello);sayHello(‘wayou‘);unmonitor(sayHello);sayHello(‘wayou‘);

Debug & undebug

Debug also receives a function name as a parameter. When the function is executed, it is automatically disconnected for debugging. Similar to a breakpoint at the function entry, it can be done through debugger, you can also find the source code in the chrome developer tool and then manually break the breakpoint.
WhileundebugThe breakpoint is removed.

Other commands are unappealing, because they can be operated through the UI of the chrome developer tool and are easier to input on the console.

Reference
  • Styled console logging in the chrome devtools (Canary)
  • Chrome console API
  • Chrome console command line API

Feel free to repost but keep the link to this page please!

Original address: incomplete guide to chrome Console

Reprinted: incomplete guide to the chrome Console

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.