Chrome Debugging JavaScript Scripts

Source: Internet
Author: User
Tags event listener file url readable stack trace chrome devtools

As the complexity of JavaScript applications increases, developers need powerful debugging tools to help them quickly identify the cause of the problem and to fix it efficiently. Chrome DevTools offers a range of useful tools to make debugging JavaScript applications no longer a pain.

In this section, we'll let you know how to use these tools by debugging Google Closure Hovercard Demo and other dynamic examples.

Note: If you are a WEB developer and want to get the latest version of DevTools, you should use Chrome Canary

SOURCE panel

The source panel allows you to debug JavaScript code. It provides a graphical interface to the V8 debugger. Use the following steps to work with the source panel:

    • Open a site, such as Google Closure hovercard Demo page or Todomvc app.
    • Open the DevTools window.
    • If Sources is not selected, it is selected manually.

The source panel allows you to view all the scripts on the page you are browsing. The icon buttons at the bottom of the panel provide a standard pause, resume, and statement-by-sentence operation, respectively. There is also a button at the bottom of the window to force a pause when an exception occurs. In different tabs, the Sources is visible, and you can open the file location and display all the scripts with just a click.

Execution control

Execution control-related buttons are at the top of the side panel, allowing you to step through the code. The available buttons are:

    • Continue: Continue executing the code until another breakpoint is encountered.
    • Step over (Progressive statement): Executes line by row to see how each row operates on the current variable. When your code calls another function, the debugger does not jump to that function's code, its focus is the current function, and Step into is the opposite.
    • Step into (procedure-by-process): Similar to statement by sentence, but click-through procedure will make the debugger take execution to the called function declaration when the function is called.
    • Step out: When you go inside a function by using the procedure, clicking the button skips the rest of the function declaration, and the debugger moves the execution to its parent function.
    • Toggle Breakpoints: Toggle breakpoints Enable, disable state while ensuring that their enabled state is not affected.

In the source panel, there are a number of related shortcut keys available:

    • Continue: Use on Mac F8 or Command + on \ other platforms Ctrl \ .
    • Step over: On Mac for F10 or Command +, on other platforms for Ctrl + .
    • Step into: On Mac for F11 or Command +, on ; other platforms Ctrl + ; .
    • Step out: on Mac for + Shift F11 or Shift + + Command , on ; other platforms for Shift + Ctrl + ; .
    • Next Call Frame: Ctrl + . . (For all platforms)
    • Previous Call Frame: Ctrl + , . (For all platforms)

If you want to see other supported shortcuts, please refer to shortcuts.

Use breakpoints to debug

Breakpoints are places where you stop or pause your code in a script for some purpose. Using breakpoints in DevTools can debug JavaScript code, DOM updates, and network calls.

Adding and removing breakpoints

In the source panel, open a copy of the JavaScript file for debugging. In the following example, we have debugged the Todoctrl.js file from AngularJS version of TODOMVC.

Click the empty glyd before the line number to set the breakpoint on that line. Then a blue mark will appear, indicating that the breakpoint has been set:

You can add multiple breakpoints. Click on the space in front of the other line to continue setting the breakpoint, and all the breakpoints you have set will be displayed in the Breakpoints option under the right side bar.

The check box before the breakpoint lets you choose whether to enable the breakpoint, and if the breakpoint is disabled, the blue label will change color.

Click on the entry of the breakpoint to jump to the corresponding line in the source file:

Click the Blue tab to delete the breakpoint.

Right-clicking the Blue tab opens a menu that includes: Continue to Here,remove breakpoint,edit Breakpoint and Disable breakpoint.

To set a conditional breakpoint, select Edit Breakpoint, or right-click the space before the line number and select Add Conditional breakpoint. In the input field, you can enter any expression that returns TRUE or false. When the condition returns True, the breakpoint interrupts the execution of the code.

Conditional breakpoints are useful when you want to analyze the code for loops or frequently triggered callback events.

Note: Sometimes you may not need to set breakpoints from the DevTools interface. Now that you want to start the debugger from your code, you can use the Debugger keyword to do this.

Using the Pause Breakpoint

When you set one or more breakpoints, return to the browser window and interact with the page. In the following example, we add a breakpoint in the Removetodo () method. Now any behavior that you want to remove the TODO option in the Todomvc app will trigger a breakpoint:

To recover the code, click the Continue button in the DevTools window or use the F8 keyboard shortcut.

When the script is paused, you can use Watch Expressinos, call Stack, and Scope Variables panel in the right sidebar.

Call stack panel

The Call stack panel shows the full execution path of the code to the pause, which allows us to drill down into the code to find the cause of the error.

If you want to see the execution path of an asynchronous JavaScript callback function, including timers and XHR events, click the Async check box.

For more information and examples on the asynchronous call stack, refer to Debuggin asynchtonous JavaScript with Chrome DevTools on the html5rocks.com Web page.

Place JavaScript files in a black box

When you put a JavaScript source file in a black box, you can't jump to that file while debugging the code. You can try it in the code you are interested in.

You can use the settings panel to put the script file in a black box, or right-click on the file in the sources panel and select Blackbox script.

For more information about black boxes, refer to the blackboxing JavaScript file

Control Desk

The Consle drawer in DevTools allows you to experiment near where the debugger is currently paused. Click the Esc key to open the console in the view and press Esc the key again to close the console.

Breakpoints in Dynamic JavaScript
    • Load Dynamic Script
    • Locate "Dynamicscript.js" in the script's drop-down option in the Sources panel and set the breakpoint on the second line.
    • Call function from dynamic script
    • The program should pause at the breakpoint at this point
    • In the DevTools window, click Continue or press F8 to continue.

Tip: Note the "//# sourceurl=dynamicscript.js" line at the end of the Dynamicscript.js file. This is a way to name the script created by the Eval function, and more information is described in the section Source Maps. You can set breakpoints for a dynamic JavaScript file only if the user provides a name for it.

Pause execution in the next JavaScript statement
    • Click the Pause button
    • Move your mouse to an area in
    • Your mouse should stop on the OnMouseOver function.
    • Click the Continue button or press f8** to continue execution

Pause at occurrence of exception
    • Click the Pause on exceptions button at the bottom of the window to switch to pause mode at the exception
    • Tick the Pause on caught Exceptinos check box
    • Raise exception!
    • The program should stop in the Raiseandcatchexception function
    • Click the Continue button or press F8 to continue execution

Pausing at an uncaught exception
    • Click the Pause on exceptions button
    • Uncheck the Pause on caught Exceptions check box
    • Raise exception!
    • At this point, if an exception is caught, the program should not stop at the RAISEANDCATCHEXCEP function
    • Raise uncaught exception!
    • You should stop at the RaiseException function at this time
    • Click the Continue button or press F8 to continue execution

Breakpoints on DOM Change events
    • Right-click on the "Parent element" below and select Inspect element from the Text menu (review elements)

      Parent Element
    • Right-click on the Elements panel element and select break on subtree modifications
    • Append child!
    • You should stop at the function call at this time appendChild
    • Click the Continue button or press F8 to continue execution

Breakpoints on the XHR
    • Click the Add button on the XHR breakpoints sidebar on the right side of the sources panel
    • In the text input go to enter "Data.txt" and then click Enter
    • Retrieve Data.txt by XHR
    • You should stop at the send function call at this time
    • Right-click on the newly created breakpoint and select Remove Breakpoint
    • Click the Continue button in the Devtools window or press F8 to continue.

Tip: To edit the URL filter, double-click the XBR breakpoint of the XHR breakpoints Sidebar, and the XHR breakpoint with the empty URL filter will match any XHR.

Breakpoints on the JavaScript event listener
    • Open the Event Listener breakpoints Sidebar on the right Scripts panel
    • Expand Mouse Options
    • Select the check box before mouseout to set the Mouseout event listener Breakpoint

    • Move your mouse to the box below
Hover me!
    • You should stop at the mouseout event handler at this time
    • Click the Continue button or press F8 to continue execution

Tip: The following events are supported
Keyboard: Release the button, press the key, enter the text
Mouse: Click, double click, mouse button Press, mouse button release, mouse hover, mouse move, mouse from the element left.
Control: Reset size, scroll, zoom, focus, lose focus, select, change, reset Clipboard: Copy, Cut, paste, beforecopy,beforecut,beforepaste load: Load, unload, REVOKE, error. DOM mutation:domactivate,domfocusin,domattrmodified,domcharacterdatamodified,domnodeinserted,  domnodeinsertedintodocument,domnoderemoved,domnoderemovedfromdocument,domsubtreemodified,domcontentloaded Device: For devices, device motion.

Long Press Resume execution

When paused, click and do not release the Restore button to let "all pauses are blocked for 500 milliseconds after recovery". This makes all breakpoints unusable in half a second, and you can use this method to go into the next loop so that you can avoid continually letting breakpoints continue to execute in order to exit the loop.

Professional advice: When using DevTools to start "Refresh" (with focus on DevTools using Ctrl + R), all pauses will be disabled until the new page starts to load (or as an alternative, until the user presses the "Pause" button). However, if you start the refresh operation from the browser's button (or use Ctrl + R when the focus is outside the DevTools), all remaining breakpoints will be hit. This can actually be useful for those who are interested in the page unloading process.

Real-time editing

In the authoring and workflow chapters, we discussed how to modify the script through the Source panel. At the breakpoint, you can also make changes by tapping the main edit panel, and you can modify the script file in real time.

    • Navigate to Google Closure Hovercard Demo
    • In the source panel, open "Mouse.js" and use Ctrl/cmd + Shift + O to navigate to the onmouseout () function

    • Click the pause button to pause debugging
    • Modify the function to add Console.log (' Moused out ') at the end
    • Use CMD + s or Ctrl + S shortcut keys to save changes, remember to confirm whether to save
    • Click the Pause/resume button to resume execution
    • When your mouse leaves the relevant location, the console will output information

This allows you to save the modified content by using DevTools without exiting the browser.

Abnormal

Let's take a look at how exceptions are handled and how to use the DevTools of Chrome for stack tracing. Exception handling is the response to an exception that occurs-except for some situations that require a specific process-and generally changes the normal process of JavaScript code execution.

Note: If you are a WEB developer and want to get the latest version of DevTools, you need to use Chrome Canary

Tracking exceptions

When the program has an exception, you can open the DevTools console (Ctrl + Shift + j/cmd + Option + J) and you will find a lot of JavaScript error messages. Each message indicates the corresponding file name and line number that you can use to navigate to the relevant location in the source code.

View exception Tracking Stack

There may be multiple execution paths that cause errors, and it is not obvious which one is wrong. As long as the DevTools window is open, the exception condition in the console appears with the full JavaScript call stack. You can expand these console information to view the stack information and navigate to the appropriate location in your code:

Pause when JavaScript has an exception

You may want to pause the execution of JavaScript and see its call stack, range variables, and the state of the application the next time the JavaScript exception occurs. The pause button () at the bottom of the Script panel allows you to switch between different anomaly modes, and the button has three states: You can choose to pause the program when all exceptions occur or just pause the program when an uncaught exception occurs or ignore all exceptions.

Printing stack Information

The log information that is output in DevTools is very helpful in understanding the execution of an application, and you can include associated stack trace information in the log information to make it more useful. There are many ways to do this.

Error.stack

Each Error object has a string property named Stack, which contains the heap trace information:

Console.trace ()

You can use concole.trace() the method to output the current JavaScript call stack, which can be used to detect code:

Console.assert ()

It's also a good idea to add assertion to your code. Whenever a console.assert() method is called and the error condition is the first argument, you will see the corresponding console record each time the expression evaluates to false:

Using Window.onerror to handle exceptions at run time

Chrome supports setting a handler function to Window.onerror. This method is called whenever a JavaScript exception is thrown in the context of a window and is not captured by any try/catch block. At the same time, the exception information, the file URL that throws the exception, and the location of the exception in the file are passed to the method as three parameters in the order shown above. You might feel like this. It is convenient to set up an error handler that can collect uncaught exception information and report it to the server.

Beautify the output format

If you're having trouble reading and debugging some simplistic JavaScript code, there's an option to beautify the output format to make these processes easier. Here's a copy of the simplistic script file that might appear in DevTools:

If you click the curly brace icon at the bottom left, the JavaScript will be converted to a more readable format. This format is also quite handy for debugging and setting breakpoints.

Source Maps

Do you expect your client code to be readable and fit for debugging, even after you've merged and scaled down your code? Now you can feel the magic of the source map.

A source map based on JSON format creates a relationship between the reduced code and the source code.

The following is an example of a simple source mapping:

  {    version : 3,    file: "out.min.js",    sourceRoot : "",    sources: ["foo.js", "bar.js"],    names: ["src", "maps", "are", "fun"],    mappings: "AAgBC,SAAQ,CAAEA"  }

Source mapping is when you shrink and merge JavaScript files to build a product, creating a mapping of the source file information. The source mapping allows DevTools to load your source files instead of the zoomed-in files. You can then use the source file to set breakpoints and debug your code. At the same time, Chrome is actually running a scaled-down code. This makes you feel like you're running a source file.

Using the source map with the correct shrink

You need to use a shrink that can create a source map to narrow down your code. Closure compilers and UGLIFYJS 2.0 are two such tools, of course, there are many other tools that support Coffeescript, SASS, and other source mappings. Refer to the Wikipedia page Source maps:languages, tools and other info.

Set DevTools

Resource Mapping (SOURCEMAP) is enabled by default (that is, Chrome 39), and if you want to double-check or enable it individually, open DevTools and click the Settings icon. Under the Sources option, view the Enable javaScript source maps. You can also check the Enable CSS source maps, but you don't need to do this in this example.

Make source Map accessible

If you want DevTools to know that a source mapping is available, verify that the code for the last line of the reduced file is not the following.

//# sourceMappingURL=/path/to/file.js.map

This line is usually added by the tool that generates the mapping, and allows DevTools to establish a link between the reduced file and the source file. In CSS, this line might be something like this: /# sourceMappingURL=style.css.map /.

If you don't want additional comments in the file, you can use the HTTP header in the JavaScript file to tell the DevTools where the source files are. This requires setting up or customizing the Web server, and this content is beyond the goal of this tutorial.

X-SourceMap: /path/to/file.js.map

Similar to annotations, the code also tells DevTools where to look for source files and associate them with the corresponding JavaScript files. This header information is also used to resolve the problem that the language referencing the source mapping does not support single-line annotations.

You should also check that your Web server is set up to support resource mapping. Some servers require a clear configuration of each file, such as Google App Engine. In this case, your source mapping should be set to set the MIME type to application/json , but Chrome will accept any type of class-tolerance declaration, for example application/octet-stream .

Take a look at the specially built font Dragr tool in Chrome, and when the source map is enabled, you will notice that the JavaScript file is not compiled and you can see all the referenced JavaScript files. This uses the source mapping, but the background is actually running the compiled code. Any errors, logs, and breakpoints are mapped to the development code, which makes debugging easier. In fact, you feel like you're running code in development.

@sourceURL and DisplayName in the event

The following sections of the source mapping declaration do not make you much easier to develop with the evals function.

This helper (@sourceURL) looks similar to the//# Sourcemappingurl property and is actually mentioned in the source mapping V3 specification. The following special comments are included in your code, and you can name the eval function and the inline scripts and styles so that they can have logical names when they are displayed in your development tool.

//# sourceURL=source.coffee
Using sourceURL
    • Navigate to Demo
    • Open the DevTools and find the Sources panel
    • Enter a name for your code
    • Click the Compile button
    • The Coffeescript source file calculates the total value and outputs it by warning
    • If you open the Sources sub-panel, you will see a new file with the file name you entered earlier. If you double-click the file to see the details, you will find that the file contains the original compiled JavaScript from the source file. The last line will have a//@sourceURL comment indicating what the source file is. This can be helpful when debugging with language abstraction.

From:http://wiki.jikexueyuan.com/project/chrome-devtools/debugging-javascript.html

Chrome Debugging JavaScript Scripts

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.