Use the chrome Console)

Source: Internet
Author: User

The console provides two main methods for developers to test web pages and applications:

Diagnose log information by using console APIs provided by the console, such as console. Log () and console. Profile ().

The instant response command window can be jointly tuned with document and chrome development tools. in the console, you can directly test the expression and use the methods provided by the command line API. For example, $ () can be used to search for elements or use profile () to open the CPU analyzer.

This article provides an overview of these two APIs and some basic usage. You can also directly view the details through the console API and command line API.

Basic operations open the Console

There are two effective ways to open the console in the debugging tool: Console tag in the main tab bar, or when you are in another label, it is displayed as a separate view (for example, in elements or sources ).

To open the console, perform any of the following operations:

  • Press and holdCommand-Option-J(Mac) orControl-shift-J(Windows/Linux ).
  • SelectView> developer> JavaScript Console.
  • PressF12> Console

You can pressESCTo open or close the separation view of the console, or clickShow/hide ConsoleButton.

Clear console history

To clear the console history, you can select one of the following methods:

  • Right-click or press Ctrl-click to select a text menu in any area of the consoleClear Console.
  • Enter clear () in the console and press enter (command line API ).
  • Enter console. Clear () and press enter (console API ).
  • Press the keyboard? KOr? L(Mac)Control-l(Windows and Linux ).

When you jump to another web page, the console clears the history by default and sets it in the Settings dialog box of the console area.Preserve log upon navigationYou can change this behavior (see console preferences ).

Console settings

The console has two global settings that can be modified in the general Settings dialog box:

  • Log xmlhttprequests-Each completed XMLHttpRequest request is displayed on the blank stage.
  • Preserve log upon navigation-Historical records are not cleared during page refresh or redirection. The default two settings do not take effect.

You can also right-click any area in the console and set it in the pop-up text menu.

 

Use of console APIs

The console API is a collection of methods provided by the console, a global object defined by the debugging tool. one of the main purposes is to output log information (such as a variable value, an object, or DOM element) to the console when your application is running. to avoid visual confusion, you can also organize the output to the console.

Console writing

The console. Log () method can pass one or more expressions as parameters and output their current values to the console. For example:

var a = document.createElement(‘p‘);a.appendChild(document.createTextNode(‘foo‘));a.appendChild(document.createTextNode(‘bar‘));console.log("Node count: " + a.childNodes.length);

Using the "+" operator to connect expressions (as shown above), you can place each of its own method parameters and connect them to rows separated by spaces.

console.log("Node count:", a.childNodes.length, "and the current time is:", Date.now());

Errors and warnings

The console. Error () method displays text information with a Red Cross icon and a red font.

function connectToServer() {    console.error("Error: %s (%i)", "Server is  not responding",500);}connectToServer();

The console. Warn () method displays text information with a yellow icon.

if(a.childNodes.length < 3 ) {    console.warn(‘Warning! Too few nodes (%d)‘, a.childNodes.length);}

Assertions

Console. the assert () method throws an exception (the second parameter) when the first parameter value is false ). for example, in the following example, when the number of subnodes of the list element is greater than 500, an error message is thrown to the console.

console.assert(list.childNodes.length < 500, "Node count is > 500");

Filter console Information

Through strict hierarchical control, you can quickly filter the console output information-errors, warnings, or standard log information-select one of the filtering options. you can click the funnel (as shown below) to select a condition you want to use.

Filter options:

  • All-Display All console output information.
  • Errors-Display only slaveConsole. Error () Output Information
  • Warnings-Display only slaveConsole. Warn () Output Information
  • Logs-Display only slaveconsole.log(),console.info()AndOutput Information of console. debug ().
  • Debug-Display only slaveConsole. timeend () and other console outputs.
Organizational output

Use in the consoleConsole. Group () andThe groupend () command can display and output a nested block on the console.

var user = "jsmith", authenticated = false;
console.group("Authentication phase");
console.log("Authenticating user ‘%s‘", user);
// authentication code here...
if (!authenticated) {
  console.log("User ‘%s‘ not authenticated.", user)
}
console.groupEnd();

Multi-layer Nesting is also possible. In the following example, create a verification phase for the log group logon process. If the user has been verified, a nested group will be created for the authorization phase.

var user = "jsmith", authenticated = true, authorized = true;
// Top-level
groupconsole.group("Authenticating user ‘%s‘", user);
if (authenticated) {
  console.log("User ‘%s‘ was authenticated", user);
  // Start nested group
  console.group("Authorizing user ‘%s‘", user);
  if (authorized) {
    console.log("User ‘%s‘ was authorized.", user);
  }
  // End nested group
  console.groupEnd();
}
// End top-level
groupconsole.groupEnd();
console.log("A group-less log trace.");

To create a default collapsed group, you can useconsole.groupCollapsed(). See the following example:

console.groupCollapsed("Authenticating user ‘%s‘", user);if (authenticated) {  ...}

String replacement and formatting

The first parameter of any log method (such as log () and error () passed to the console may contain one or more placeholders. A placeholder consists of a % and a declaration that should be used to insert a Letter of the value type (such as a % s string ). the placeholder identifies where to replace the parameter value provided after it.

The following example uses the % s (string) and % d (integer) placeholders to insert values to the console output.

console.log("%s has %d points", "Sam", "100");

The output is "Sam has 100 points"

The following table lists some placeholder information:

Placeholder Description
%s String.
%dOr%i Integer.
%f Floating Point Number.
%o The link of the DOM element.
%O JS object link.
%c CSS format string.

In the following example, The placeholder % d is used to convert the number of subnodes of the document into an integer, And the placeholder % F is used to format the time as the timestamp.

console.log("Node count: %d, and the time is %f.", document.childNodes.length, Date.now());

DOM elements & JS objects

By default, When you output a DOM element to the console, it is displayed in XML format, such as the element panel:

console.log(document.body.firstElementChild);

Of course, you can also use console. dir () to display all the attributes of an object.

console.dir(document.body.firstElementChild);

Equivalent placeholders can also be used through console. Log ()% O to implement the above results.

console.log("%O", document.body.firstElementChild);
Console & CSS

Use the placeholder % C in console. Log () to implement the output style on the console.

console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");

Time Detection

Console. Time () andConsole. the timeend () method helps us detect how long it takes to complete a method. console. time () is placed before the task to start detection to enable time detection. Add the console at the end of the task. timeend () to stop, the time difference will be output to the console.

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

Note: The same string must be used in console. Time () and timeend (). Otherwise, you may not get the expected result.

Breakpoint debugging

You can enable the debug mode to write data in your JS Code.The following example shows the debug mode when the brightness () method is executed:

brightness : function() {    
  debugger;
  var r = Math.floor(this.red*255);
  var g = Math.floor(this.green*255);
  var b = Math.floor(this.blue*255);
  return (r * 77 + g * 150 + b * 29) >> 8;
}

 

Appendix: An interesting debugging Article breakpoint actions in JavaScript -- Brian Arnold

 

Command Line API

Continue in the next period...

 

 

 

Console API: http://visionsky.blog.51cto.com/733317/543789

 

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.