How do you debug a JavaScript program

Source: Internet
Author: User
Tags event listener chrome developer chrome developer tools

How do you debug a JavaScript program? The most primitive way to print content on a page with alert () is to use Console.log () to output content on the JavaScript console with a slightly improved approach. Well, using these two methods really solves the debugging problems of many small JavaScript scripts. But it's a pity to put the more powerful developer tools in Chrome. This article focuses on the JavaScript breakpoint settings and debugging capabilities, which are Sources Panel (formerly called Scripts). If you are proficient in the various Java debugging techniques in Eclipse, the concepts here are similar. The version of Chrome that was used to write this article is 25.0.1364.172.

Basic Environment

The left side of Sourcespanel is the content source, including the various resources on the page. Among them, also divide Sources and Content scripts. Sources is the various resources contained in the page itself, it is organized according to the fields appearing in the page, which is our concern. The asynchronous loading of the JS file will also appear here after loading. Content scripts is an extension of Chrome that is organized by an extended ID, which is actually a resource embedded in the page, and they can also read and write to the DOM. Developers who write and debug such extensions are concerned about them, and if your browser does not have any extensions installed, then content scripts will not see anything.

The intermediate main area of the Sources Panel is used to display the contents of the left resource file.

On the right side of the Sources Panel is the debug ribbon, with the topmost row of buttons paused/resumed, stepping, stepping in, stepping out, disabling/enabling all breakpoints. The following are the various specific functional areas. described later.

Note that the left and right sides of the area may be shrunk by default on both sides of the display, click on both sides of the telescopic button display. When the left area is displayed, the default is auto-shrinking, and clicking the Pin button next to it will not shrink back.

There are also some feature buttons at the bottom that are useful.

To set breakpoints on source code

Through the left content source, open the corresponding JavaScript file, the mouse click on the file line number can set and delete breakpoints. Each breakpoint that you add appears in the Breakpoints list in the debug area on the right, and clicking on the list breakpoint will position you on the break point in the content area. If you have multiple files and multiple breakpoints, it is convenient to use the breakpoints in the breakpoints list to quickly locate them.

There are two states for each breakpoint that has been added: active and disabled. The breakpoint you just added is active, and the disabled state is the one that retains the breakpoint but temporarily cancels the breakpoint function. In the Breakpoints list, there is a check box before each breakpoint, and unchecking disables the breakpoint. Breakpoints can also be disabled in the right-click menu of the breakpoint location. You can also temporarily disable all added breakpoints on the right-hand ribbon button, and then click Restore Status.

Conditional Breakpoint : In the right-click menu of the breakpoint, select "Edit breakpoint ..." To set the condition for triggering a breakpoint, which is to write an expression that is true when the breakpoint is triggered. View breakpoint's environment Call stack: When a breakpoint is stopped, the call stack on the right side of the debug area shows the stack of methods that the current breakpoint is in, such as having a function g () where the function f () is called, and I set a breakpoint in F (), then I am in the console The execution of the function g () triggers a breakpoint, and its call stack is displayed as follows:

The top is f () and then G (). Each layer in the call stack is called a frame, and clicking on each frame can jump to the call point of the frame.

In addition, the current frame can be restarted on the frame with the right-click menu, which is executed from the beginning of the frame. For example, Restart frame on a frame of function f (), the breakpoint jumps to the beginning of f () and the value of the variable in the context is restored. This combination of variable modification and editing of code and other functions, you can be repeated in the current frame debugging, without refreshing the page to re-trigger the breakpoint. View variables

Below the call Stack list is a list of Scope Variables, where you can see the values of local variables and global variables at this time. Code to execute the selection

When debugging a breakpoint, you can see the current value of the expression by selecting the variable or expression you want to view, and then executing "Evaluate in Console" On the right-click menu. The Interrupt/Continue button on the right side of the debug area of the next JavaScript statement you want to execute also has a function that, when the breakpoint is not triggered, the button will go into the "ready" interrupt state, and the next time the page executes the JavaScript statement, it will be automatically interrupted. For example, the code that executes when a click action is triggered. Temporarily modifying JavaScript code usually we are accustomed to debugging code: Modify the Code → refresh the page → recheck, such a loop. But in fact, Chrome can temporarily modify the contents of the JS file, save (Ctrl+s) can be effective immediately, combined with the Console and other functions can be re-debugged immediately. But notice that this change is temporary, refresh the page changes will be gone.

Breakpoint at exception

You can see the button below the interface, which is the switch that sets the interrupt when the program runs with an exception. Clicking this button toggles between 3 states:

Default encountered exception not interrupted

All exceptions will be interrupted, including captured cases

Interrupts only if an uncaught exception occurs

Explain the difference between state 2 and State 3.

try{
Throw ' a exception ';
}catch (e) {
Console.log (e);
}

The code in the above try encounters an exception, but the catch code behind it catches the exception. If all exceptions are interrupted, the code is automatically interrupted when it executes the throw statement that produces the exception, and if it is interrupted only by an uncaught exception, there is no interruption. In general, we are more concerned about situations where an uncaught exception is encountered.

To set breakpoints on DOM elements

Sometimes we need to listen to a DOM being modified, without worrying about which line of code is being modified (and there may be multiple changes to it). Then we can set breakpoints directly on the DOM.

See, in the Element review Elements panel in the right-click menu on an element you can set three different conditions of the breakpoint: child node modified itself property modification itself node is deleted selected, Sources panel in the right side of the DOM breakpoints list will appear in the DOM Breakpoint. Once executed to make the appropriate modifications to the DOM, the code stops there, as shown in.

XHR Breakpoint

The right side of the debug area has a XHR breakpoints, click + and enter the URL contains a string to listen to the URL of the Ajax request, the input content is equivalent to the URL of the filter. If you do not fill in anything, then listen to all XHR requests. Once the XHR call is triggered, it is interrupted at Request.send ().

Trigger Breakpoint by Event type

The event Listener list on the right side of the debug area, which lists the various possible types of events. Tick the corresponding event type and the JavaScript code that triggered the event of that type is automatically interrupted.

debugging shortcut keys

The shortcut keys in all development tools can be found in the settings in the lower right corner of the interface. Breakpoints are typically used for F8, F10, F11, or SHITF+F11, but function keys such as F10 on Mac OS may conflict with the system's default shortcut keys. It doesn't matter, they can use cmd+/, cmd+ ', cmd+ respectively; , shift+cmd+; Replace. @ sourceURL give eval code a name sometimes some very dynamic code is created in the form of a string using the Eval () function in the current Javascript context instead of being loaded as a standalone JS file. You can't find this file on the left side of the content area, so it's hard to debug. In fact, we just add a line "//@ Sourceurl=name" to the end of the code created by eval to give this code a name (the browser treats this particular form of comment in particular) so it will appear on the left side of the content area, as if you had loaded a JS file with the specified name. You can set breakpoints and debug. , we execute a piece of code through eval and use sourceURL to name it dynamicscript.js, and the "file" appears on the left-hand side of the execution, and its content is the content of the eval. You can also look at this example for the dynamically compiled Coffeescript code naming:

var coffee = Coffeescript.compile (code.value) + "//@ sourceurl=" + (Evalname.value | | "coffeeeeeeee!");
eval (coffee);

In fact,//@ sourceURL can not only be used in eval code, any JS file, or even Javascript Console input code can be used, the same effect! The format code (pretty Print) button is used to reformat the messy code into beautiful code, such as some of the compressed JS files are almost impossible to see, and more impossible to debug. Click Format, then click to cancel Formatting. Before beautification
Post-Landscaping reference: Chrome Developer Tools Official documentation

How do you debug a JavaScript program

Related Article

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.