diff --git a/docs/console-files/console-context-menu.png b/docs/console-files/console-context-menu.png deleted file mode 100644 index 996485b..0000000 Binary files a/docs/console-files/console-context-menu.png and /dev/null differ diff --git a/docs/console-files/console-count.png b/docs/console-files/console-count.png new file mode 100644 index 0000000..aceb661 Binary files /dev/null and b/docs/console-files/console-count.png differ diff --git a/docs/console-files/console-in-drawer.png b/docs/console-files/console-in-drawer.png new file mode 100644 index 0000000..f21ba51 Binary files /dev/null and b/docs/console-files/console-in-drawer.png differ diff --git a/docs/console-files/frame-selection.png b/docs/console-files/frame-selection.png new file mode 100644 index 0000000..84e925e Binary files /dev/null and b/docs/console-files/frame-selection.png differ diff --git a/docs/console-files/inspect2.png b/docs/console-files/inspect2.png deleted file mode 100644 index 3dc15b8..0000000 Binary files a/docs/console-files/inspect2.png and /dev/null differ diff --git a/docs/console-files/locations-between-frames.png b/docs/console-files/locations-between-frames.png new file mode 100644 index 0000000..a5400e6 Binary files /dev/null and b/docs/console-files/locations-between-frames.png differ diff --git a/docs/console-files/multiline-expression.png b/docs/console-files/multiline-expression.png deleted file mode 100644 index 1cd887b..0000000 Binary files a/docs/console-files/multiline-expression.png and /dev/null differ diff --git a/docs/console-files/recent-selection.png b/docs/console-files/recent-selection.png deleted file mode 100755 index 5c55b1b..0000000 Binary files a/docs/console-files/recent-selection.png and /dev/null differ diff --git a/docs/console-files/select-login-btn.png b/docs/console-files/select-login-btn.png deleted file mode 100644 index 974be9c..0000000 Binary files a/docs/console-files/select-login-btn.png and /dev/null differ diff --git a/docs/console-files/select-multiple-login.png b/docs/console-files/select-multiple-login.png deleted file mode 100644 index aa06ef7..0000000 Binary files a/docs/console-files/select-multiple-login.png and /dev/null differ diff --git a/docs/console-files/table-arrays.png b/docs/console-files/table-arrays.png new file mode 100644 index 0000000..bd243ab Binary files /dev/null and b/docs/console-files/table-arrays.png differ diff --git a/docs/console-files/table-people-objects.png b/docs/console-files/table-people-objects.png new file mode 100644 index 0000000..6a490ba Binary files /dev/null and b/docs/console-files/table-people-objects.png differ diff --git a/docs/console-files/time-annotation-on-timeline.png b/docs/console-files/time-annotation-on-timeline.png new file mode 100644 index 0000000..412c4a7 Binary files /dev/null and b/docs/console-files/time-annotation-on-timeline.png differ diff --git a/docs/console-files/timestamps-disabled.png b/docs/console-files/timestamps-disabled.png new file mode 100644 index 0000000..69d2a58 Binary files /dev/null and b/docs/console-files/timestamps-disabled.png differ diff --git a/docs/console-files/timestamps-enabled.png b/docs/console-files/timestamps-enabled.png new file mode 100644 index 0000000..920bd79 Binary files /dev/null and b/docs/console-files/timestamps-enabled.png differ diff --git a/docs/console.html b/docs/console.html new file mode 100644 index 0000000..a7ba6e9 --- /dev/null +++ b/docs/console.html @@ -0,0 +1,909 @@ +{{+bindTo:partials.standard_devtools_article}} + +

Using the Console

+ +
+

+ Utilizing the console gives you the ability to: +

+ +

+ You also may evaluate normal JavaScript expressions. + This documentation provides an overview and common uses of the console. + You may browse the Console API and Command Line API reference material to understand more functionality. +

+
+ +
+

Basic Operation

+ + +
+

Opening the Console

+

+ The JavaScript Console is available in two places. + The Console panel provides primary access. + It also is available from within any other panel by using the Drawer. + To open the Console tab, do one of the following: +

+ + +
+ Console panel view +
+ A clean console view. +
+
+ +

+ To open the drawer console press the Esc key on your keyboard or click the Show Drawer button in the upper right corner of the Chrome DevTools window. +

+ +
+ Console split-view +
+ The console in the drawer while on the elements panel. +
+
+
+ +
+

Clearing the console history

+

+ To clear the console's history, do one of the following: +

+ +
+ +
+

Message Stacking

+

+ The console will stack consecutive messages that contain the same output. + This helps keep the information provided to you as concise as possible. +

+ +
+ + + + + + + + + + + + + +
Timestamps disabled (default)Timestamps enabled
Timestamps disabledTimestamps enabled
+
+ Examples of the two stacking states. +
+
+ +
+
+ Sample code for testing console stack modes. +
+
msgs = ['hello', 'world', 'there'];
+for (i = 0; i < 20; i++) console.log(msgs[Math.floor((i/3)%3)])
+
+
+
+ +
+

Frame Selection

+

+ The console can operate within different frames of the page. + The primary page is the top frame for the document. + An iframe element for example would create its own frame context. + You may specify the frame by using the dropdown beside the filter button. +

+ +
+ frame selection +
+ Selecting a secondary frame. +
+
+ +
+ locations between frames +
+ This image shows how the window origin has changed between the top frame and the selected secondary frame. +
+
+
+
+ +
+

Using the Console API

+

+ The Console API is collection of methods provided by the global `console` object defined by DevTools. + One of the API's main purposes is to log information to the console while your application is running. + You can also group output visually in the console to reduce visual clutter. +

+ +
+

Writing to the console

+

+ The console.log() method takes one or more expressions as parameters and writes their current values to the console. +

+ +
+
A simple write to the console.
+
+
var a = document.createElement('p');
+a.appendChild(document.createTextNode('foo'));
+a.appendChild(document.createTextNode('bar'));
+console.log("Node count: " + a.childNodes.length);
+
+
+
+ Basic log +
+ Display of the example code in the console. +
+
+
+ +

+ Multiple parameters will concatenate into a space-delimited line. +

+ +
+
console.log() with multiple parameters
+
+
console.log("Node count:", a.childNodes.length, "and the current time is:", Date.now());
+
+
+ Log Multiple +
+ Output of multiple parameter console.log() +
+
+
+
+ +
+

Errors and Warnings

+

+ Errors and warnings act the same way as normal logging. + The difference is error() and warn() have styles to bring attention to them. + The console.error() method displays a red icon along with red message text. + The console.warn() method displays a yellow warning icon with the message text. +

+ +
+
Using console warn and error methods.
+
+
Using the error() method.
+
+
function connectToServer() {
+    console.error("Error: %s (%i)", "Server is  not responding",500);
+}
+connectToServer();
+
+
+
+ Error example output +
+ How connectToServer() displays in the console. +
+
+
+ +
+
Using the warn() method.
+
+
if(a.childNodes.length < 3 ) {
+    console.warn('Warning! Too few nodes (%d)', a.childNodes.length);
+}
+
+
+
+ Warn example +
+ Example warning output. +
+
+
+
+
+ +
+

Assertions

+

+ The console.assert() method conditionally displays an error string (its second parameter) only if its first parameter evaluates to false. +

+
+
A simple assertion and how it displays.
+
+
The following code will cause an error message in the console only if the number of child nodes belonging to the list element is greater than 500.
+
+
console.assert(list.childNodes.length < 500, "Node count is > 500");
+
+
+
+ Assertion failed +
+ How an assertion failure displays in the console. +
+
+
+
+ +
+

Filtering console output

+

+ You can filter console output by its severity level by selecting one of the filter options. + Activate filters under the filter funnel icon located in the upper-left corner of the console panel. + The following filter options are available: +

+ +
+
All
+
Shows all console output.
+ +
Errors
+
Only show output from console.error().
+ +
Warnings
+
Only show output from console.warn().
+ +
Info
+
Only show output from console.info(). + +
Logs
+
Only show output from console.log().
+ +
Debug
+
Only show output from console.timeEnd() and console.debug().
+
+ +
+ Filtering errors +
+ Filter enabled for showing only errors. +
+
+
+ +
+

Grouping Output

+

+ You can group related output together with the group commands. + The group command takes a single string parameter to set the name of the group. + The console will begin to group all subsequent output together. + To end the grouping you only need to call groupEnd(). +

+ +
+
Simple grouping example
+
+
Example code:
+
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();
+
+
+
+
Example output
+ Simple console group output +
+
+ +

+ Log groups may also nest within each other. + This is useful to see a large group in smaller pieces at a time. +

+ +
+
+ This example shows a log group for the authentication phase of a login process. +
+
+
The code:
+
var user = "jsmith", authenticated = true, authorized = true;
+// Top-level group
+console.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 group
+console.groupEnd();
+console.log("A group-less log trace.");
+
+
+
+ Nested console group output +
+ Nested groups output in the console. +
+
+
+ +

+ When you are using groups heavily it can be very useful to not see everything as it happens. + For these times you can automatically collapse groups by calling groupCollapsed() instead of group(). +

+ +
+
console.groupCollapsed() usage
+
+
Example code:
+
console.groupCollapsed("Authenticating user '%s'", user);
+if (authenticated) {
+    ...
+}
+console.groupEnd();
+
+
+
+ Initially collapsed group +
+ groupCollapsed() output. +
+
+
+
+ +
+

Viewing structured data

+ +

+ The table() method provides an easy way to view similar data objects. + This will take the properties of an object and create a header. + Row data comes from each indexes properties value. +

+ +
+
+ A table in the console using two arrays. +
+
+
Example code:
+
console.table([{a:1, b:2, c:3}, {a:"foo", b:false, c:undefined}]);
+console.table([[1,2,3], [2,3,4]]);
+
+
+
+
The output of the example code.
+ console table display +
+
+ +

+ The second parameter to table() is optional. + You may define an array containing the property strings you wish to display. +

+ +
+
+ A console table using a collection of objects. +
+
+
Example code:
+

+function Person(firstName, lastName, age) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+  this.age = age;
+}
+
+var family = {};
+family.mother = new Person("Susan", "Doyle", 32);
+family.father = new Person("John", "Doyle", 33);
+family.daughter = new Person("Lily", "Doyle", 5);
+family.son = new Person("Mike", "Doyle", 8);
+
+console.table(family, ["firstName", "lastName", "age"]);
+
+
+
+
The output of the example code.
+ console output with table objects +
+
+ +
+ +
+

String substitution and formatting

+ +

+ The first parameter passed to any of the logging methods may contain one or more format specifiers. + A format specifier consists of a % symbol followed by a letter that indicates the formatting that applies to the value. + The parameters following the string apply to the placeholders in order. +

+ +
+
+ The following example uses the string and digit formatters to insert values into the output string. + You will see Sam has 100 points in the console. +
+
console.log("%s has %d points", "Sam", 100);
+
+ +

The full list of format specifiers are as follows:

+ +
+
%s
+
Formats the value as a string
+ +
%d
+
%i
+
Formats the value as an integer.
+ +
%f
+
Formats the value as a floating point value.
+ +
%o
+
Formats the value as an expandable DOM element. As seen in the Elements panel.
+ +
%O
+
Formats the value as an expandable JavaScript object.
+ +
%c
+
Applies CSS style rules to the output string as specified by the second parameter.
+
+ +
+
+ This example uses the digit specifier to format the value of document.childNodes.length. + It also uses the floating point specifier to format the value of Date.now(). +
+
+
The code:
+
console.log("Node count: %d, and the time is %f.", document.childNodes.length, Date.now());
+
+
+ Example subsitution output +
+ The output of the previous code sample. +
+
+
+
+ +
+

Formatting DOM elements as JavaScript objects

+ +

+ When you log a DOM element to the console it displays in an XML format. + This is the same view as the Elements panel. + To display the JavaScript representation you may either use the dir() method or the object format specifier in a log() statement. +

+ +
+
The different views for logging an element.
+ + + + + + + + + + + + + + +
log() viewdir() view
Element loggedElement logged using dir()
+
+
+ +
+

Styling console output with CSS

+

+ The CSS format specifier allows you to customize the display in the console. + Start the string with the specifier and give the style you wish to apply as the second parameter. +

+ +
+
Styling log information
+
+
Example code:
+
console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
+
+
+ Formatted string +
Example code output.
+
+
+
+ +
+

Measuring how long something takes

+

+ A timer starts by calling the time() method. + You must pass a string to the method to identify the time marker. + When you want to end the measurement call timeEnd() and pass it the same string passed to the initializer. + The console logs the label and time elapsed when the timeEnd() method fires. +

+ +
+
Example code and output for timing JavaScript execution.
+
+
Example Code:
+
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");
+
+
+
+
Output in the console:
+ Time elapsed +
+
+ +

+ When a Timeline recording is taking place during a time() operation it will annotate the timeline as well. + This is useful when tracing what your application does and where it comes from. +

+
+ Time annotation on timeline +
+ How an annotation on the timeline looks from time(). +
+
+
+ +
+

Marking the Timeline

+

+ The Timeline panel provides a complete overview of where the engine spends time. + You can add a mark to the timeline from the console with the timeStamp(). + This is a simple way to correlate events in your application with other events. +

+ +

Note: The timeStamp() method only functions while a Timeline recording is in progress.

+ +

+ The timeStamp() annotates the Timeline in the following places: +

+ + +
+
+
Example code:
+
function AddResult(name, result) {
+    console.timeStamp("Adding result");
+    var text = name + ': ' + result;
+    var results = document.getElementById("results");
+    results.innerHTML += (text + "<br>");
+}
+
+
+
+ timestamps in the timeline +
+ Timestamps in the timeline. +
+
+
+
+ +
+

Setting breakpoints in JavaScript

+

+ The debugger; statement will begin a debugging session. + This is equivalent to setting a breakpoint at this line in the script. +

+ +
+
Calling brightness() begins the debug session.
+
+
Example code:
+
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;
+}
+
+
+
+
Example output:
+ Debugger activated +
+
+
+ +
+

Counting statement executions

+ +

+ The count() method will log the provided string along with the number of times the same string has been provided. + The string may have dynamic content. + When the exact statement is given to count() on the same line the number will increment. +

+ +
+
+ An example count() with some dynamic content. +
+
+
Example code:
+
function login(user) {
+    console.count("Login called for user " + user);
+}
+
+users = [ // by last name since we have too many Pauls.
+    'Irish',
+    'Bakaus',
+    'Kinlan'
+];
+
+users.forEach(function(element, index, array) {
+    login(element);
+});
+
+login(users[0]);
+
+
+
+
Output of the code sample:
+ console count example output +
+
+
+
+ +
+

Using the Command Line API

+

+ The console is more powerful than a simple log output directory. + It also is a full terminal prompt in the scope of the current web page. + The Command Line API offers the following features: +

+ + +
+

Evaluating expressions

+

+ The console will evaluate any JavaScript expression you provide when pressing Enter. + It provides auto-completion and tab-completion. + As you type an expression property name suggestions appear. + If there are multiple matches and will cycle through them. + Pressing will select the current suggestion. + For a single suggestion Tab will also select the suggestion. +

+
+ Simple expressions in the console. +
+ Some simple expressions in the console. +
+
+
+ +
+

Selecting Elements

+

+ There are a few shortcuts for selecting elements. + These save you valuable time when compared to typing out their standard counterparts. +

+ +
+
$()
+
+ Returns the first element that matches the specified CSS selector. + It is a shortcut for document.querySelector(). +
+ +
$$()
+
+ Returns an array of all the elements that match the specified CSS selector. + This is an alias for document.querySelectorAll() +
+ +
$x()
+
+ Returns an array of elements that match the specified XPath. +
+
+ +
+
Examples of target selection:
+
$('code') // Returns the first code element in the document.
+$$('figure') // Returns an array of all figure elements in the document.
+$x('html/body/p') // Returns an array of all paragraphs in the document body.
+
+
+
+ +
+

Inspecting DOM elements and JavaScript heap objects

+

+ The inspect() function takes a DOM element or JavaScript reference as a parameter. + If you provide a DOM element the DevTools will go to the Elements panel and display that element. + If you provide a JavaScript reference then it will go to the Profile panel. +

+
+
+ When this code executes in your console on this page, it will grab this figure and display it on the Elements panel. + This takes advantage of the $_ property to get the output of the last evaluated expression. +
+
$('[data-target="inspecting-dom-elements-example"]')
+inspect($_)
+
+
+
+ +
+

Accessing recently selected elements and objects

+

+ The console stores the last five element and object selections. + As you select an element in the Elements panel or an object in the Profiles panel, that pushes onto the history stack. + $x provides access to the history stack. + Remember computers begin counting from 0; this means the latest item is $0 and the oldest item is $4. +

+
+ +
+

Monitoring events

+

+ The monitorEvents() method instructs the DevTools to log information on the specified targets. + The first parameter is the object to monitor. + All events return if the second parameter is not provided. + To specify the events to listen to you may pass either a string or an array of strings as the second parameter. +

+
+
Listen to click events on the body of the page.
+
monitorEvents(document.body, "click");
+
+

+ If a supported event type that the DevTools maps to a set of standard event names then it will listen to the events for that type. + The Command Line API has a full mapping of event types to the events they cover. +

+

+ To stop monitoring events you call the unmonitorEvents() method and give it the object to stop monitoring. +

+
+
+ Stop listening to events on the body object. +
+
unmonitorEvents(document.body);
+
+
+ +
+

Controlling the CPU Profiler

+

+ The profile() function begins a JavaScript CPU profile. + You may pass in a string to name the profile as well. + To stop a profile call profileEnd() in the same way you called the initializer. +

+
+
+
+ Create a new profile without providing a name. +
+
profile()
+profileEnd()
+
+
+
+
Example profile
+ Profile panel +
+
+

+ If you provide a label that is the heading. + Profiles group together if you create multiple profiles with the same label. +

+
+
+
+ Example code: +
+
profile("init")
+profileEnd("init")
+profile("init")
+profileEnd("init")
+
+
+
+
Result in the profiles panel:
+ Grouped profiles created by the example code. +
+
+

+ Multiple CPU profiles can operate at once. + You also are not required to close them out in creation order. +

+
+
+
Nested profiles closed in same order:
+
profile("A")
+profile("B")
+profileEnd("A")
+profileEnd("B")
+
+
+
+
Nested profiles closed in alternate order:
+
profile("A")
+profile("B")
+profileEnd("B")
+profileEnd("A")
+
+
+
+
+ +
+ +
+
+

Settings

+

+ The Console has four settings you can modify in the general tab of the DevTools settings dialog: +

+
+
Hide network messages
+
Instructs the console to not show logs from network issues. For example, 404 and 500 series errors will not be logged.
+ +
Log XMLHttpRequests
+
Determines if the console logs each XMLHttpRequest.
+ +
Preserve log upon navigation
+
Determines if the console history is not deleted when you navigate to another page.
+ +
Show timestamps
+
When a statement is made to the console this will display the timestamp for the call. This will disable message stacking.
+
+
+
+ +
+

Summary

+

+ The Chrome DevTools provides a robust console. + You should now understand how to begin using this to store information and grab elements. + This functionality is still scratching the surface of possibilities. + The web is your playground and these are your building blocks. +

+
+ + +{{/partials.standard_devtools_article}} diff --git a/docs/console.md b/docs/console.md deleted file mode 100644 index c51a9a4..0000000 --- a/docs/console.md +++ /dev/null @@ -1,391 +0,0 @@ -{{+bindTo:partials.standard_devtools_article}} - -# Using the Console - -The JavaScript Console provides two primary functions for developers testing web pages and applications: - -* A place to log diagnostic information using methods provided by the [Console API](console-api.md), such as [console.log()](console-api.md#consolelogobject-object), or [console.profile()](console-api.md#consoleprofilelabel). -* A shell prompt where you can enter commands and interact with the document and the Chrome DevTools. You can evaluate expressions directly in the Console, and can also use the methods provided by the [Command Line API](commandline-api.md), such as [$()](commandline-api.md#selector) command for selecting elements, or [profile()](commandline-api.md#profilename) to start the CPU profiler. - -This documentation provides an overview and common uses of these two APIs. You can also browse the [Console API](console-api.md) and [Command Line API](commandline-api.md) reference guides. - - - -## Basic operation - -### Opening the Console - -The JavaScript Console is available in two modes within Chrome DevTools: the primary Console tab, or as a split-view you can display while on another tab (such as Elements or Sources). - -To open the Console tab, do one of the following: - -* Use the keyboard shortcut **Command - Option - J** (Mac) or **Control -Shift -J** (Windows/Linux). -* Select **View > Developer > JavaScript Console**. - -![Console panel view](console-files/console1.png) - -To toggle a split-view of the Console on another tab, press the **Esc** key on your keyboard, or click the **Show/Hide Console** button in the bottom left corner of the Chrome DevTools window. In the following screenshot the Console split-view is shown with the Elements panel. - -![Console split-view](console-files/console-split-view.png) - -### Clearing the console history - -To clear the console's history, do one of the following: - -* Right-click or Ctrl-click anywhere in the Console and choose **Clear Console** from the context menu that appears. -* Enter the [**clear()**](commandline-api.md#clear) Command Line API at the shell prompt. -* Invoke [**console.clear()**](console-api.md#consoleclear) Console API from JavaScript. -* Use the keyboard shortcut **⌘K** or **⌃L** (Mac) **Control - L** (Windows and Linux). - -By default, the console history is cleared when you navigate to another page. You can change this behavior by enabling **Preserve log upon navigation** in the Console area of the Settings dialog (see [Console preferences](#consolepreferences)). - -### Console settings - -The Console has two global settings you can modify in the General tab of the DevTools Settings dialog: - -* **Log XMLHTTPRequests**—determines if each XMLHTTPRequest is logged to the Console panel. -* **Preserve log upon navigation**—determines if console history for the current page is preserved when you navigate to another page. By default, both of these settings are disabled. - -You can also change these settings by right-clicking anywhere in the Console to bring up the context menu. - -![Console panel view](console-files/console-context-menu.png) - - - -## Using the Console API - -The Console API is collection of methods provided by the global `console` object defined by DevTools. One of the API's main purposes is to [log information](#writing-to-the-console) (such as a property value, or an entire objects or DOM element) to the console while your application is running. You can also group output visually in the console to reduce visual clutter. - -### Writing to the console - -The [console.log()](console-api.md#consolelogobject-object) method takes one or more expressions as parameters and writes 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); - -![Console log output](console-files/log-basic.png) - -Instead of concatenating expressions together with the "+" operator (as shown above), you can put each in its own method parameter and they will be joined together in a space-delimited line. - - console.log("Node count:", a.childNodes.length, "and the current time is:", Date.now()); - -![Console log output](console-files/log-multiple.png) - -### Errors and warnings - -The [`console.error()`](console-api.md#consoleerrorobject-object) method displays a red icon along with the message text, which is colored red. - - function connectToServer() { - console.error("Error: %s (%i)", "Server is not responding",500); - } - connectToServer(); - -![](console-files/error-server-not-resp.png) - -The [`console.warn()`](console-api.md#consolewarnobject-object) method displays a yellow warning icon with the message text. - - if(a.childNodes.length < 3 ) { - console.warn('Warning! Too few nodes (%d)', a.childNodes.length); - } - -![Example of console.warn()](console-files/warning-too-few-nodes.png) - -### Assertions - -The [`console.assert()`](console-api.md#consoleassertexpression-object) method conditionally displays an error string (its second parameter) only if its first parameter evaluates to `false`. For instance, in the following example an error message is written to the console only if the number of child nodes belonging to the `list` element is greater than 500. - - console.assert(list.childNodes.length < 500, "Node count is > 500"); - -![Example of console.assert()](console-files/assert-failed.png) - -### Filtering console output ### - -You can quickly filter console output by its severity level--errors, warning, or standard log statements--by selecting one of the filter options. Click on the filter funnel (as shown below) and then select which filter you want to use. - -![Only show console.error() output](console-files/filter-errors.png) - -Filter options: - -* **All**—Shows all console output. -* **Errors**—Only show output from `console.error()` -* **Warnings**—Only show output from `console.warn()` -* **Logs**—Only show output from `console.log()`, `console.info()` and `console.debug()`. -* **Debug**—Only show output from `console.timeEnd()` and other console output. - -### Grouping output - -You can visually group related console output statements together in the console with the [`console.group()`](console-api.md#consolegroupobject-object) and [`groupEnd()`](console-api.md#consolegroupend) commands. - -
-    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();
-
- -![Logging group example](console-files/group.png) - -You can also nest logging groups. In the following example a logging group is created for the authentication phase of a login process. If the user is authenticated, a nested group is created for the authorization phase. - -
-    var user = "jsmith", authenticated = true, authorized = true;     
- // Top-level group
- console.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 group
- console.groupEnd();
- console.log("A group-less log trace.");
-
- - -![Nested logging group example](console-files/nestedgroup.png) - -To create a group that is initially collapsed, use [`console.groupCollapsed()`](console-api.md#consolegroupcollapsed) instead of `console.group()`, as shown below: - - console.groupCollapsed("Authenticating user '%s'", user); - if (authenticated) { - ... - } - -![Initially collapsed group](console-files/groupcollapsed.png) - -### String substitution and formatting - -The first parameter you pass to any of the console's logging methods (`log()` or `error()`, for example) may contain one or more _format specifiers_. A format specifier consists of a **`%`** symbol followed by a letter that indicates the formatting that should be applied to the inserted value (`%s` for strings, for example). The format specifier identifies where to substitute a value provided by a subsequent parameter value. - -The following example using the `%s` (string) and `%d` (integer) formatters to insert values into the output string. - - console.log("%s has %d points", "Sam", "100"); - -This would result in "Sam has 100 points" being logged to the console. - -The following table lists the supported format specifiers and the formatting they apply: - -|Format specifier|Description ------------------|--------------- -`%s` | Formats the value as a string. -`%d` or `%i` | Formats the value as an integer. -`%f` | Formats the object as a floating point value. -`%o` | Formats the value as an expandable DOM element (as in the Elements panel). -`%O` | Formats the value as an expandable JavaScript object. -`%c` | Applies CSS style rules to output string specified by the second parameter. - -In the following example the `%d` format specifier is substituted with the value of `document.childNodes.length` and formatted as an integer; the `%f` format specifier is substituted with the value returned by `Date.now()`, which is formatted as a floating point number. - - console.log("Node count: %d, and the time is %f.", document.childNodes.length, Date.now()); - -![Using format specifiers](console-files/format-substitution.png) - -### Formatting DOM elements as JavaScript objects - -By default, when you log a DOM element to the console it's displayed in an XML format, as in the Elements panel: - - console.log(document.body.firstElementChild) - -![](console-files/log-element.png) - -You can also log an element's JavaScript representation with the `console.dir()` method: - - console.dir(document.body.firstElementChild); - -![](console-files/dir-element.png) - -Equivalently, you can us the `%O` [format specifier](#string-substitution-and-formatting) with `console.log()`: - - console.log("%O", document.body.firstElementChild); - -### Styling console output with CSS ### - -You use the `%c` format specifier to apply custom CSS rules to any string you write to the Console with [`console.log()`](#writingtotheconsole) or related methods. - - console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large"); - -![Styling console output with CSS](console-files/format-string.png) - -### Measuring how long something takes - -You can use the [`console.time()`](console-api.md#consoletimelabel) and [`console.timeEnd()`](console-api.md#consoletimeendlabel) methods to measure how long a function or operation in your code takes to complete. You call `console.time()` at the point in your code where you want to start the timer and `console.timeEnd()` to stop the timer. The elapsed time between these two calls is displayed in 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"); - -![Example of using console.time() and timeEnd()](console-files/time-duration.png) - -Note: You must pass the same string to `console.time()` and `timeEnd()` for the timer to finish as expected. - -### Marking the Timeline - -The [Timeline panel](timeline.md) gives you a complete overview of where time is spent when loading and using your web app or page. The [`console.timeStamp()`](console-api.md#consoletimestamplabel) method marks the Timeline at the moment it was executed. This provides an easy way to correlate events in your application with other browser-related events, such as layout or paints. - -Note: The `console.timeStamp()` method only functions while a Timeline recording is in progress. - -In the following example the Timeline is marked when the application enters the `AddResult()` function's implementation. - - function AddResult(name, result) { - console.timeStamp("Adding result"); - var text = name + ': ' + result; - var results = document.getElementById("results"); - results.innerHTML += (text + "
"); - } - -As shown in the following screenshot, the `timeStamp()` command annotates the Timeline in the following places: - -* A yellow vertical line in the Timeline's summary and detail views. -* A record is added to the list of recorded events. - -![Timeline showing custom timestamp](console-files/timestamp2.png) - -### Setting breakpoints in JavaScript ### - -You can start a debugging session from your JavaScript code by calling the [`debugger`](console-api.md#debugger) command. For instance, in the following example the JavaScript debugger is opened when an object's `brightness()` function is invoked: - - 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; - } - -![Example of using debugger command](console-files/debugger.png) - - - - - -## Using the Command Line API - -In addition to being a place where you can log information from your application, the Console is also a shell prompt where you can directly evaluate expressions or issue commands provided by the [Command Line API](commandline-api.md). This API provides the following features: - -* Convenience functions for selecting DOM elements -* Methods for controlling the CPU profiler -* Aliases for a number of Console API methods -* Monitoring events -* View event listeners registered on objects - -### Evaluating expressions ### - -The Console attempts to evaluate any JavaScript expression you enter at the shell prompt, upon pressing the Return or Enter key. The Console provides auto-completion and tab-completion. As you type expressions, property names are automatically suggested. If there are multiple properties with the same prefix, pressing the Tab key cycles through them. Pressing the right arrow key accepts the current suggestion. The current suggestion is also accepted by pressing the Tab key if there is only one matched property. - -![](console-files/evaluate-expressions.png) - -To enter a multi-line expression at the shell prompt (such as a function definition) press Shift+Enter between lines. - -![](console-files/multiline-expression.png) - -### Selecting elements - -The Command Line API provides several methods to access DOM elements in your application. For example, the [**`$()`**](commandline-api.md#selector) method returns the first element that matches the specified CSS selector, just like [`document.querySelector()`](http://docs.webplatform.org/wiki/css/selectors_api/querySelector). For instance, the following code returns the element with the ID "loginBtn". - - $('#loginBtn'); - -![](console-files/select-login-btn.png) - -The [**`$$()`**](commandline-api.md#selector-1) command returns an array of all the elements that match the specified CSS selector, just like [`document.querySelectorAll()`](http://docs.webplatform.org/wiki/css/selectors_api/querySelectorAll). For instance, the following displays selects all `