Unexpected Chrome debugging features

Source: Internet
Author: User
Tags chrome developer

I did not think that Chrome features such a powerful, not only can use Console.log only, encountered such a good text must be collected, thank God, the original address of this article is: http://www.cnblogs.com/Wayou/p/ Chrome-console-tips-and-tricks.html, remember here to spur their efforts to forge ahead!

Chrome's developer tools are strong enough to have no friends, especially with its rich interface-friendly console, which can be used with the following benefits:

    • Higher "force lattice" faster development and debugging "stronger" into the class of frontender"
    • Bug everywhere "console Dafa good"

We all use log, but few people use it very well console.error , console.warn and then sort the information out to the console.
They have little difference in function, meaning they classify the information that is output to the console, or make them more semantic.
The semantics represented by each are as follows:

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

When the above log method is used properly, it is convenient to select a specific type of information in the console.


If we cooperate console.group with each other console.groupEnd , the idea of this sort of management can be used to the fullest. This is suitable for the development of a very large module of many complex web apps, the individual log information is grouped into groups with the name of their own namespace.

console.group("app.foo");console.log("来自foo模块的信息 blah blah blah...");console.groupEnd();console.group("app.bar");console.log("来自bar模块的信息 blah blah blah...");console.groupEnd();

And about console.log , has already been playing bad. It all comes down to the API provided by Chrome: The first parameter can contain some formatting instructions such as %c .

For example, to hello world make a beautiful wedding dress and then pull out to see people:

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

If you don't feel good enough, apply the most gorgeous CSS styles you can write, such as gradients. So you can get the following gorgeous effect:

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;‘);

All kinds of strokes of the rhythm Ah ~

Look at the dense code above do not panic, the console.log() second parameter is all pure CSS to control the style, you will not be unfamiliar. In the first argument, you can take an escape instruction that begins with a percent sign, such as the command used to output a styled text above %c . See the official API documentation for this table for more detailed instructions.

If it's not enough, let's log some pictures, even ... Motion diagram?
Yes, you have to have a picture first, 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 swing above the bean than the rabbit is a kind of urge to smoke it a face.

In addition to this, console.table it is directly in the form of tabular data output, can not praise too much!
Borrow an example of a it that you have written before:

var data = [{‘品名‘: ‘杜雷斯‘, ‘数量‘: 4}, {‘品名‘: ‘冈本‘, ‘数量‘: 3}];console.table(data);

In addition, the console.log() parameters are received, separated by commas, and eventually the output will be concatenated with whitespace characters.



When you want the code to meet certain conditions to output the information to the console, then you do not have to write if or ternary expression to achieve the goal, cosole.assert it is a good tool in this scenario, it will first assert the incoming expression, only the expression is false to output the corresponding information to the console.

var isDebug=false;console.assert(isDebug,‘开发中的log信息。。。‘);


In addition to the conditional output scenario, there are also common scenarios that are counted.
When you want to count how many times a piece of code is executed, you don't have to write the logic yourself, and the built-in console.count can be very competent for such a task.

function foo(){//其他函数逻辑blah blah。。。console.count(‘foo 被执行的次数:‘);}foo();foo();foo();


Output DOM nodes as JavaScript objects to the console
Instead console.log , the DOM node is exported directly to the structure of the DOM tree, which is consistent with the structure seen during element review. Different forms of presentation, the same elegance, a variety of positions any choice is convenient and thoughtful.


Console.time & Console.timeend

Output Some debugging information is the most common function of the console, of course, its function is much more than this. As with some performance tests, this can also be done conveniently here.
For example, when you need to consider the time-consuming situation of code execution, you can use it console.time console.timeEnd to do this.

Here are examples of official documents:

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, we can also choose to write our own code to clock:

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 also see, with built-in console.time is how convenient, save yourself to write code to calculate the workload. It is also worth mentioning that the results obtained by invoking the built-in are console.time more accurate and reliable than the time difference that you manually calculate.

Console.profile & Console.timelime

When you want to view information about CPU usage, you can use console.profile mates console.profileEnd to accomplish this requirement.
This feature can be done via the UI interface, which has a tab in the Chrome developer tool Profile .

Similar to this, the function console.timeLine is to console.timeLineEnd start recording a timeline, as well as using the tags in the Chrome developer tool Timeline .

So in my opinion, these two methods are a bit of a chicken, because they can be done through the Operation interface. But at least he provides an interactive command-line approach, or a lot of poses for you to choose from.


stack trace related debugging can be used console.trace . This can also be done through the UI interface. When the code is interrupted, you can Call Stack view the relevant stack information in the panel.

Described above are hanging in the window.console object below the method, collectively known as the console API, the next method is exactly called the command, is chrome built-in provided, used in the console, they are collectively called command line API.


It seems that the American DAO is always favored by programmers and various programming languages. "You see PHP code to know how much phper love Money," in the chrome console, the $ utility is quite a lot and convenient.
$_The command returns the result of the most recent expression execution, with the same function as pressing the UP ARROW key again, but it can be used as a variable in your next expression:


The above $_ needs to be understood in order to be used properly, while $0~$4 represents the last 5 DOM nodes you have chosen.
What do you mean? Right-click on the page to select 审查元素 , and then in the pop-up DOM node tree above the random click, these points are the point of the nodes will be recorded, and $0 will return the most recent point selected DOM node, and so on, and so on, returned the last point selected DOM nodes, up to 5 saved, if not enough 5, is returned undefined .

What's more, the Chrome console natively supports jquery-like selectors, which means you can use $ the familiar CSS selector to select the DOM node and how familiar it is.


$ (selector) returns the first DOM element that satisfies the selection criteria.
Stripping off her hypocritical cloak is in fact $(selector) a native JavaScript document.querySelector() wrapper.
At the same time, another command $$(selector) returns a collection of all elements that satisfy the selection criteria, which is the encapsulation of the pair document.querySelectorAll() .



This command allows you to copy the contents obtained from the console to the Clipboard.


Then you can stick around:

After reading this command line, witty you are not with the brain hole full of me, came up with the idea: that is, through this command can be copied in JavaScript, so do not rely on flash plugin.
But the reality is cruel, as previously mentioned, here the console command can only be executed in the console environment, because he does not attach to any global variables such as window , so in fact, in the JS code is not access to this copy method, so from the code level to invoke the replication function is not possible to talk about. I hope one day the browser will provide the corresponding JS implementation bar ~

Keys & Values

This is a pair of friends. The former returns data that consists of all the property names of the passed-in object, which returns an array of all property 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, for example function a , each time it a is executed, it outputs a message in the console that contains the name of the function a and the parameters passed in when it was executed.

and Unmonitor (function) is used to stop this monitoring.

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 automatically breaks down for debugging, similar to a breakpoint at the entrance of the function, can be done by debugger, and can be manually interrupted by finding the appropriate source code in the Chrome developer tool.
Instead, undebug the breakpoint is lifted.

There are many other commands that let people not say the desire, because better can be done through the Chrome Developer tool UI interface and more convenient than the console input.

Unexpected Chrome debugging features

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.