Home > Article > Web Front-end > An incomplete guide to the Chrome console_html/css_WEB-ITnose
This article is reproduced from http://www.cnblogs.com/Wayou/p/chrome-console-tips-and-tricks.html
Chrome’s developer tools It is so powerful that it has no friends, especially its feature-rich console with a friendly interface. When used properly, it can have the following effects:
Everyone can use log, but few people make good use of console.error, console .warn etc. classify and organize the information output to the console.
There is not much difference in their functions. The significance is to classify the information output to the console, or to make them more semantic.
The semantics represented by each are as follows:
When the above log method is used properly, you can easily choose to view specific types of information on the console.
console.log('一颗红心向太阳','吼吼~'); console.info('楼上药不能停!'); console.warn('楼上嘴太贱!'); console.error('楼上关你毛事?');
If you cooperate with console.group and console.groupEnd, you can take this idea of classification management to its extreme. This is suitable for grouping respective log information into groups named after their respective namespaces when developing a large-scale and complex Web APP with many modules.
console.group("app.foo"); console.log("来自foo模块的信息 blah blah blah..."); console.groupEnd(); console.group("app.bar"); console.log("来自bar模块的信息 blah blah blah..."); console.groupEnd();
As for console.log, it has already been ruined. Everything comes from Chrome providing such an API: the first parameter can contain some formatting instructions such as %c.
For example, make a beautiful wedding dress for hello world and show it to people:
console.log('%chello world','font-size:25px;color:red;');
If you think it’s not satisfying enough, then write what you can Apply the most gorgeous CSS styles, such as gradients. So you can get the following gorgeous effects:
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;');
Various rhythms of big moves~
Don’t panic when you look at the dense code above. The second parameter of console.log() is pure CSS used to control the style, which you will be familiar with. The first parameter can contain an escape command starting with a percent sign, such as the %c command used when outputting styled text above. For more detailed instructions, see this table in the official API documentation.
If it’s not fun enough, let’s log some pictures, even. . . GIF?
Yes, you must 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;");
Looking at the swaying Dobby Rabbit above, do you have the urge to slap it in the face?
In addition, console.table directly outputs the data in the form of a table. I can’t like it too much!
Borrowing an example from a blog post I wrote before:
var data = [{'品名': '杜雷斯', '数量': 4}, {'品名': '冈本', '数量': 3}]; console.table(data);
In addition, console.log() receives variable parameters, separated by commas, and will eventually be output They will be concatenated with whitespace characters.
console.log('%c你好','color:red;','小明','你知道小红被妈妈打了么');
When you want the code to meet certain conditions, output information to the console, then you don’t have to write if or ternary Expression to achieve the goal, cosole.assert is a good tool in such a scenario. It will first assert the incoming expression, and only output the corresponding information to the console when the expression is false.
var isDebug=false; console.assert(isDebug,'开发中的log信息。。。');
In addition to conditional output scenarios, there is also a common scenario of counting.
When you want to count how many times a certain piece of code has been executed, you don’t have to write the relevant logic yourself. The built-in console.count can handle such a task very well.
function foo(){ //其他函数逻辑blah blah。。。 console.count('foo 被执行的次数:'); } foo(); foo(); foo();
Output the DOM node to the console in the form of a JavaScript object
And console.log directly outputs the DOM node The point is output in the structure of the DOM tree, which is consistent with the structure seen during element inspection. Different forms of presentation, the same elegance, and various positions for you to choose. Anyway, it is convenient and considerate.
console.dir(document.body); console.log(document.body);
Outputting some debugging information is the most commonly used function of the console, of course, its function is much more than that. When doing some performance testing, it can also be conveniently done here.
For example, when you need to consider the time it takes to execute a piece of code, you can use console.time and console.timeEnd to do this.
Here is an example borrowed from the official documentation:
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 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 have also seen how convenient it is to use the built-in console.time, saving you the workload of writing your own code to calculate. It is also worth mentioning that the results obtained by calling the built-in console.time are more accurate and reliable than the time difference calculated manually.
When you want to view information related to CPU usage, you can use console.profile with console.profileEnd to complete this requirement.
This function can be completed through the UI interface. There is a tab in the Chrome developer tools called Profile.
与此类似的功能还有console.timeLine配合 console.timeLineEnd,它的作用是开始记录一段时间轴,同样可以通过Chrome开发者工具里的Timeline 标签来进行相应操作。
所以在我看来这两个方法有点鸡肋,因为都可以通过操作界面来完成。但至少他提供了一种命令行方式的交互,还是多了种姿势供选择吧。
堆栈跟踪相关的调试可以使用console.trace。这个同样可以通过UI界面完成。当代码被打断点后,可以在Call Stack面板中查看相关堆栈信息。
上面介绍的都是挂在window.console这个对象下面的方法,统称为Console API,接下来的这些方法确切地说应该叫命令,是Chrome内置提供,在控制台中使用的,他们统称为Command Line API。
似乎美刀总是被程序员及各种编程语言所青睐「你看看PHP代码就知道PHPer有多爱钱了」,在Chrome的控制台里,$用处还真是蛮多且方便的。
$_命令返回最近一次表达式执行的结果,功能跟按向上的方向键再回车是一样的,但它可以做为一个变量使用在你接下来的表达式中:
2+2//回车,再 $_+1//回车得5
上面的$_需要领悟其奥义才能使用得当,而$0~$4则代表了最近5个你选择过的DOM节点。
什么意思?在页面右击选择审查元素,然后在弹出来的DOM结点树上面随便点选,这些被点过的节点会被记录下来,而$0会返回最近一次点选的DOM结点,以此类推,$1返回的是上上次点选的DOM节点,最多保存了5个,如果不够5个,则返回undefined。
另外值得一赞的是,Chrome 控制台中原生支持类jQuery的选择器,也就是说你可以用$加上熟悉的css选择器来选择DOM节点,多么滴熟悉。
$('body')
$(selector)返回的是满足选择条件的首个DOM元素。
剥去她伪善的外衣,其实$(selector)是原生JavaScript document.querySelector() 的封装。
同时另一个命令$$(selector)返回的是所有满足选择条件的元素的一个集合,是对document.querySelectorAll() 的封装。
$$('div')
通过此命令可以将在控制台获取到的内容复制到剪贴板。
copy(document.body)
然后你就可以到处粘了:
看完此条命令行,机智的你是不是跟脑洞全开的我一样,冒出了这样一个想法:那就是通过这个命令可以在JavaScript里进行复制操作从而不用依赖Flash插件了。
But现实是残酷的,如之前所述的,这里的控制台命令只能在控制台中环境中执行,因为他不依附于任何全局变量比如window,所以其实在JS代码里是访问不了这个copy方法的,所以从代码层面来调用复制功能也就无从谈起。但愿有天浏览器会提供相应的JS实现吧~
这是一对基友。前者返回传入对象所有属性名组成的数据,后者返回所有属性值组成的数组。具体请看下面的例子:
var tboy={name:'wayou',gender:'unknown',hobby:'opposite to the gender'}; keys(tboy); values(tboy);
monitor(function),它接收一个函数名作为参数,比如function a,每次a被执行了,都会在控制台输出一条信息,里面包含了函数的名称a及执行时所传入的参数。
而unmonitor(function)便是用来停止这一监听。
function sayHello(name){ alert('hello,'+name); } monitor(sayHello); sayHello('wayou'); unmonitor(sayHello); sayHello('wayou');
debug同样也是接收一个函数名作为参数。当该函数执行时自动断下来以供调试,类似于在该函数的入口处打了个断点,可以通过debugger来做到,同时也可以通过在Chrome开发者工具里找到相应源码然后手动打断点。
而undebug 则是解除该断点。
而其他还有好些命令则让人没有说的欲望,因为好些都可以通过Chrome开发者工具的UI界面来操作并且比用在控制台输入要方便。