Partager via


Using the Console to view errors and debug

Use the Console tool to view errors and other messages, send debug output, inspect JavaScript objects and XML nodes, and to run JavaScript in the context of the selected window or frame.

A window into your code

The primary use for the Console tool is to communicate into and out of running webpages:

  • In: You run JavaScript to view and change values in running webpages, add functions to running code, and run debug code on the fly.
  • Out: Internet Explorer and JavaScript code deliver status, error, and debug messages to developers, including inspectable JavaScript objects and DOM Nodes.

Sending info to the Console

  • Selecting your execution target
  • Messages Internet Explorer sends to the console
  • Messages developers can send to the console from code
  • Managing messages for readability

Selecting your execution target

New in Windows 8.1 Update, the Console has a Target drop-down menu just above the Console output pane. If the webpage you're viewing has an iframe element in it, select the iframe from the Target menu to run Console commands solely in the scope of the iframe. If your webpage has no iframes, the only selection will be "_top."

Messages Internet Explorer sends to the console

By default settings, the Console won't show any messages until you start it. Start it by opening the F12 developer tools, and selecting the Console tool (CTRL + 2). You can also open the Console within another tool using the Show console button in the upper-right of the tools pane or CTRL + `.

From this image, you can see that Internet Explorer system messages have three categories. They are (in order):

  • Information: Non-critical information you might want to know.
  • Warning: Possible errors in your webpage that don't necessarily break it, but may cause unexpected behavior.
  • Error: Critical errors that cause code not to run. For more info, see a list of Internet Explorer error codes used in the console.

Starting with Cumulative Security Update for Internet Explorer (KB2976627), the F12 developer tools will also show an indicator over the Console icon, alerting you to the number of error messages.

These messages can be filtered out of the Console output. The icons for each message type at the top of the Console pane act as toggles. Click one to remove its associated message type, then again to return it. You can also right-click in the Console output and find check boxes for each type in the context menu.

When you click the file name that follows a message, you open the Debugger tool and load the file in the script pane.

New in Windows 8.1 Update, another toggle is added next to the message types, on the right. When the Clear on navigate icon is highlighted, the console clears every time the browser navigates to a new webpage. When it isn't highlighted, the browser preserves the contents of the Console, but messages from prior webpages are grayed out to better visually indicate they are not from the current page.

In prior versions of the F12 tools, output directed to the Console was not recorded during a browsing session until the console had been opened. For developers who need the console to record messages at all times, Windows 8.1 Update adds the Always record developer console messages option. To find the option:

  • Open the Internet Options window from the Tools menu.
  • On the Advanced tab, in the Browsing section, you'll see Always record developer console messages .

For best browsing performance, we recommend you have the Always record developer console messages option turned off when you're not actively debugging your own content.

Messages developers can send to the console from code

The Console Debugging API gives you methods for sending info out from your code to the console. The info breaks down into these types:

  • Custom messages
  • Inspectable objects and nodes
  • Counters
  • Timers
  • Assertions
  • Traces and profiles

Custom messages

You have four options for custom messages. Three use the format of system messages: console.info() for information messages, console.warn() for warnings, and console.error() for errors. The fourth, console.log() presents plain text with no alert icon. All four take the same forms of argument for the message.

  • Just text:

    console.log('This is some text');
    
    This is some text
    
  • Just a variable:

    var mytext = 'This is some text';
    console.log(mytext);
    
    This is some text
    
  • Mixed text and variables:

    var mytext = 'pieces';
    var myval = 0;
    console.log("The number of " + mytext + "is " + myval);
    
    The number of pieces is 0
    
  • Variable Substitution:

    var mytext = 'pieces';
    var myval = 5;
    console.log("The number of %s is %d", mytext, myval);
    
    The number of pieces is 5
    

    Variable substitution has five variable types:

    • %s - string
    • %d - integer
    • %i - integer
    • %f - float
    • %o - object
    • %b - binary
    • %x - hexadecimal
    • %e - exponent

    The variable types control how the variable is presented. For example, a float value represented by an integer variable type is displayed as an integer.

Inspectable objects and nodes

Inspectable objects are new in Internet Explorer 11. They show up in the console in a collapsed tree format with expandable nodes.

To display an inspectable JavaScript object, send it to the console using console.dir()

To display an inspectable DOM node, send it to the console using console.dirxml()

<div id="thediv">
   <p>Click the button to show this div as a JavaScript object and a 
   <em>DOM</em> node.</p>
   <button id="thebutton">show it</button>
</div>
<script>
  document.getElementById('thebutton').addEventListener('click', function(e){
    var divid = document.getElementById('thediv');
    console.log('Showing the div element as a DOM node.');  
    console.dirxml(divid);
    console.log('Showing the div element as a JavaScript object.');
    console.dir(divid);
    console.log('Showing the div element via a plain console.log.');
    console.log(divid);
    console.log('Showing the click event via a plain console.log.');
    console.log(e);
    console.log('Argument logging for %s', thediv.id, thediv)
  });
</script>

Use the arrows to the left to expand objects and nodes.

Right-clicking DOM nodes provide an Evaluate as Object option in the context menu. If you select that option, you send the node to the console as an object. Similarly, JavaScript objects that represent DOM nodes offer an Evaluate as HTML option in their context menus.

New in Windows 8.1 Update, the console gives you more intelligent logging. For example, when displayed to the console via console.log(), the div element is displayed as an inspectable DOM node, but the click event is displayed as an inspectable JavaScript object. Even when there's text being output, if console.log() has an HTML element or JavaScript object as an argument, the output is inspectable.

Counters

While setting up a counter in code is relatively easy, it's also a repetitive task. To speed up developer workflow, the Console Debugging API provides a simple shorthand.

Use console.count() with a string containing a counter label as its argument. The first use with a specific label establishes a counter in the Console output. Subsequent uses of console.count() with the same label increment the counter. To reset the counter to zero, use console.countReset() with the label.

console.count('mylabel');
for(var i = 0; i < 10; i++){
  console.count('mylabel');
}
mylabel:         11

Timers

Like creating counters, creating a timer within code is relatively easy, but the Console Debugging API provides a simple shorthand that makes it even easier.

Use console.time() anywhere in your code to begin a timer and console.timeEnd() to end the timer and send the result to the console. If you want to label your timer or need more than one timer, pass a string with a unique label as the argument for both the console.time() and console.timeEnd() methods. If you don't pass an argument, the methods use "default" as the label.

A new time-related method in Cumulative Security Update for Internet Explorer (KB2976627) is the console.timeStamp(). It will output a timestamp to the console, showing the number of milliseconds since the current webpage loaded. If you put a number or string as the method's parameter, it will be used as a label, overriding the default label of "timestamp." When you use it during a UI Responsiveness profiling session, in addition to its console output, it will add a user mark to the session timeline with the time since the session was initiated.

Assertions

Assertions are another shorthand for speeding up developer workflow. If the first argument used with console.assert() evaluates to false, it runs console.error(), using the assertion's additional arguments for the error message.

Use this one line of code:

console.assert(f < 25, 'f is not less than %d, but is instead %o', 25, f);

And it's equivalent to writing:

if(!(f < 25)){
  console.error('f is not less than %d, but is instead %o', 25, f)
}

In the example code, we used %o to output the variable. Because the evaluation above will fail if the variable's value isn't a number, using %o makes it possible to see the variable as it is instead of cast into a specific type.

Traces and profiles

Understanding where your code is being called from, what code is running, and how long that execution takes can be useful in analyzing slowness or unexpected behavior.

A stack trace shows you the execution path your code took to reach it, from the trace request upward through the path. Use console.trace() in your code to show a stack trace.

This code...

function a(){
  c();
}
function b(){
  c();
}
function c(){
  console.trace()
}
function d(){
  b();
}

a();
d();

...displays this output in the console.

console.trace()
at c (https://www.contoso.com/trace.html:24:3)
at a (https://www.contoso.com/trace.html:18:3)
at Global code (https://www.contoso.com/trace.html:30:1)
console.trace()
at c (https://www.contoso.com/trace.html:24:3)
at b (https://www.contoso.com/trace.html:21:3)
at d (https://www.contoso.com/trace.html:27:3)
at Global code (https://www.contoso.com/trace.html:31:1)

In other instances, seeing every bit of code being run between two points can be very useful. The Profiler is the best tool for this, but in some cases more precision than a manual stop and start may be needed.

To precisely start and stop the Profiler from within your code, use console.profile() to start recording a Profiler session, and console.profileEnd() to stop it.

Pass a string to console.profile() as the method's argument to use it as the name for your profiling report.

Caution  Overlapping profiling sessions can create unexpected results. Use console.trace() in place of console.profile() for a first test run to make sure you won't be calling console.profile() more than once before you end the profiling session. If you find you're getting more traces than you expected, that might be your problem.

 

Managing messages for readability

Organizing messages into groups.

With all the types of messages and content that get sent to the console, keeping track of them can be difficult. Use the following commands to keep things more orderly:

  • console.group() begins a collapsible group in an expanded state. Every message sent to the console after this command is placed in the group until the console.groupEnd() method is used. If a string is provided as the first argument for the method, the string is used as a label for the group.
  • console.groupCollapsed() begins a collapsible group in a collapsed state. In all other respects, it behaves like console.group().
  • console.groupEnd() closes the most recently opened group.
  • console.clear() deletes all messages currently displayed in the console.

Groups can be nested within one another for more detailed levels of grouping.

To turn different types of messages on and off, use filtering.

At the top of the Console tool are icons for error, warning, and informational messages with a count of each type next to them. Click an icon to toggle the display of that message type on or off. When toggled off, that type of message is hidden, but not deleted, and can be restored by toggling that message type on again.

Right-clicking within the console output displays a context menu with check box toggles for the three main message types plus messages sent using console.log().

In Cumulative Security Update for Internet Explorer (KB2976627), CTRL + L was added as a quick keyboard shortcut to clear all the messages and output in the Console tool.

Sending JavaScript into the Console

The console not only displays output from code, but provides an interface to execute code as well. Just enter any valid JavaScript at the bottom of the Console, in the command line pane.

All script entered in the command line executes in the global scope of the currently selected window. If your webpage is built with a frameset or iframes, those frames load their own documents in their own windows.

To target the window of a frameset frame or an iframe, use the cd() command, with the frame/iframe's name or ID attribute as the argument. For example, you have a frame with the name microsoftFrame and you're loading the Microsoft homepage in it.

cd(microsoftFrame);
Current window: www.microsoft.com/en-us/default.aspx

Important  Note that there were no quotes around the name of the frame. Only pass the unquoted name or ID value as the parameter.

 

To return to the top level window, use cd() with no argument.

Selecting elements in the Console

Console selectors are new in IE11. These provide simple shorthands for quickly selecting elements in your DOM structure. They are:

Important  If code in a webpage assigns a function to $ or $$, that function overrides the console selector functions while the console is interacting with that page or its frames.

 

The multiline command line

Sending in single line commands is useful, but some tasks require executing longer scripts. Click the double up-arrow symbol to expand the command line. In multiline mode, enter as many lines as you need, then click the green arrow symbol to execute it in the console.

The Console Debugging API

Console error messages in F12 developer tools

F12 updates in kb2976627