preface

To do a good job, he must sharpen his tools. Recently, when I write code, I feel more and more that the code is not difficult, but how to debug when the code goes wrong and how to trace the source, which is the most difficult.

In response to this request, I decided to write a practical series on debugging. I was not going to write this base chapter, for the sake of completeness. (Do not spray if you do not like it)

Note that the following yifenghua. Win domain logoff, replaced by https://hua1995116.github.io/myblog/

Three chapters are planned

1. Rapid Debug Combat 1 (Browser – Basics)

2. Rapid Debug Combat ii (Browser – Online Part 1)

3. Rapid Debug (Node-webpack plugin, Babel plugin,vue source code)

So the example passes in the following environment.

Operating system: MacOS 10.13.4

Chrome: Version 72.0.3626.81 (official) (64-bit)

Breakpoint debugging JS

Many of you are still using console.log to debug your code frequently. Breakpoints have two advantages:

  • With console.log(), you need to manually open the source code, look for the relevant code, insert the console.log() statement, and then reload the page to see the messages in the console. Breakpoints allow you to pause code without knowing its structure.

  • In the console.log() statement, you need to explicitly specify each value to check. With breakpoints, DevTools displays all variable values in a timely manner when paused. Sometimes variables can affect your code without you knowing it.

The problem

1. Open: hua1995116. Making. IO/myblog/exam…

2. Enter 5 in the Number 1 text box.

3. Enter 1 in the Number 2 text box.

4. Click Add Number 1 and Number 2. The label below the button says 5 + 1 = 51. This is going to be 6. That’s what we need to fix.

interface

Step 1: Repeat the error

1. Press Command+Option+I (Mac) or Control+Shift+I (Windows or Linux) to start DevTools. This shortcut opens the Console panel.

2. Click the Sources TAB.

Step 3: Pause the code with breakpoints

If you take a step back and think about how your application works, you can infer from experience that using the click event listener associated with the Add Number 1 and Number 2 buttons does not compute the sum correctly (5 + 1 = 51). Therefore, you may need to pause the code while the Click listener is running. Event Listener Breakpoints enable you to do this:

  1. In the JavaScript Debugging pane, click Event Listener Breakpoints to expand the section. DevTools displays a list of expandable event categories such as Animation and Clipboard.
  2. Next to the Mouse event category, click the Expand Expand icon. DevTools displays a list of mouse events such as Click and Mousedown. There is a check box next to each event.
  3. Check the click check box. DevTools is now set to automatically pause any click event listener when it runs.
  4. Go back to the demo page and click Add Number 1 and Number 2 again. DevTools pauses the demo and highlights a line of code in the Sources panel. DevTools should pause at this line:
function onClick() {
Copy the code

If you pause at another line of code, press Resume Script Execution until you pause at the correct line of code.

Step through your code

A common cause of error is that scripts are executed in the wrong order. You can step through the code one line at a time to check the execution of the code and find exactly where the execution order is out of whack. Try it now:

On the Sources panel of DevTools, click Step into Next Function Call to Step into the next function call to Step through the execution of the onClick() function one line at a time. DevTools highlights this line of code:

if (inputsAreEmpty()) {
Copy the code

Click Step over Next function Call to Step over the next function call. DevTools executes but does not enter inputsAreEmpty(). Notice how DevTools skips a few lines of code. This is because inputsAreEmpty() evaluates to false, so the code block for the if statement is not executed.

This is the basic idea of stepping through code. If you look at the code in get-started, you’ll see that the error is probably somewhere in the updateLabel() function. Instead of stepping through each line of code, you can use another breakpoint to pause code closer to where it is most likely to go wrong.

Set a line of code breakpoint

Line-of-code breakpoints are the most common type of breakpoint. If you want to pause on a line of code, use a line breakpoint:

Take a look at the last line in updateLabel() :

label.textContent = addend1 + '+' + addend2 + '=' + sum;
Copy the code

On the left side of the line, you can see that the line number is 32. Click on the 32. DevTools places a blue icon above the 32. This means that there is a line breakpoint on this line of code. DevTools now always pauses before executing this line of code.

Click Resume Script Execution to continue the script execution. The script continues to execute until line 32. On lines 29, 30, and 31, DevTools prints the values of addend1, addend2, and sum to the right of the semicolons.

Checking variable values

The addend1, addend2, and sum values are suspected to be incorrect. These values are in quotes, which means they are strings. This assumption helps to explain the error. More information can now be gathered. DevTools provides a number of tools for checking variable values.

Method 1: Scope pane When paused on a line of code, the Scope pane displays the local and global variables currently defined, along with their values. Closure variables are also shown (if applicable). Double-click a variable value to edit it. If no line of code is paused, the Scope pane is empty.

Method 2: Monitor the expression Watch Expressions tag lets you monitor variable values over time. As the name implies, monitoring expressions are not limited to monitoring variables. You can store any valid JavaScript expression in a monitor expression. Try it now:

Click the Watch TAB. Click Add Expression to Add an Expression. Type typeof sum. Press the Enter key. DevTools displays typeof sum: “string”. The value to the right of the colon is the result of the monitoring expression.

As you might guess, sum should be evaluated as a number, but it turns out to be a string. It has now been established that this was the cause of the error.

Method 3: The console in addition to viewing console.log() messages, you can use the console to evaluate any JavaScript statement. For debugging, you can use the console to test potential solutions to errors. Try it now:

If you haven’t already opened the Console drawer navigation bar, press Escape to open it. The navigation bar opens at the bottom of the DevTools window. On the Console, type parseInt(addend1) + parseInt(addend2). This statement is valid because you pause at specific lines of code where addend1 and addend2 are in range. Press the Enter key. DevTools evaluates the statement and prints out 6, which is what you expect the demo page to produce.

Applied correction method

You have found a way to correct the error. The next step is to try to use the fix method by editing the code and re-running the demo. You don’t have to leave DevTools to apply fixes. You can edit JavaScript code directly from within the DevTools UI. Try it now:

  1. Click Resume Script Execution to continue the script execution.
  2. inIn the Code Editor, will be line 31var sum = addend1 + addend2Replace withvar sum = parseInt(addend1) + parseInt(addend2). 3. Press theCommand+S (Mac)Control+S (Windows, Linux)To save the changes.
  3. Click Deactivate BreakPoints to Deactivate breakpoints. It turns blue to indicate that it is active. After this setting, DevTools ignores any breakpoints you have set.
  4. Try running the demo with different values. Now the demo will calculate correctly.

Overview of the use of various breakpoints

Breakpoint types situation
Lines of code In the exact code area.
Conditional line In the exact code area, and only if some other condition holds.
DOM In the code that changes or removes a particular DOM node or child.
XHR When XHR urls contain string patterns.
Event listener In code that runs after events such as Click are triggered.
abnormal In the line of code that throws a caught or uncaught exception.
function Anytime a particular function is called.

Line breakpoint

When you know the exact code area to investigate, you can use a line of code breakpoint. DevTools always pauses before executing this line of code.

Set a line breakpoint in DevTools:

  1. Click on the Sources TAB.
  2. Open the file that contains the line of code you want to interrupt.
  3. Go to line of code.
  4. To the left of the code line is the row number column. Click on the row number column. A blue icon appears at the top of the row number column.

Line breakpoints in code

Calls to the Debugger in code can be paused on this line. This is equivalent to using a line of code breakpoint, except that the breakpoint is set in the code, not in the DevTools interface.

console.log('a');
console.log('b');
debugger;
console.log('c');
Copy the code

Conditional line breakpoints

Conditional line breakpoints can be used if you know the exact code area to investigate, but just want to pause while some other condition holds.

To set conditional line breakpoints:

  1. Click on the Sources TAB.
  2. Open the file that contains the line of code you want to interrupt.
  3. Go to line of code.
  4. To the left of the code line is the row number column. Right click on the row number column.
  5. Select Add Conditional BreakPoint. A dialog box appears below the line of code.
  6. Enter criteria in the dialog box.
  7. According to theEnterKey to activate breakpoints. An orange icon appears at the top of the row number column.

Manage line breakpoints

Use the Breakpoints pane to disable or remove line Breakpoints from a single location.

The Breakpoints pane displays two line Breakpoints: one at line 15 of get-started. Js and the other at line 32

  • Check the box next to the entry to disable the breakpoint.
  • Right-click on the entry to remove the breakpoint.
  • Right-click anywhere in the Breakpoints pane to deactivate all Breakpoints, deactivate all Breakpoints, or remove all Breakpoints. Disabling all breakpoints is equivalent to unchecking every breakpoint. Deactivating all breakpoints causes DevTools to ignore all line-of-code breakpoints, but at the same time keeps them in the enabled state so that they remain in the same state as before deactivating them.

Breakpoints

DOM change breakpoints

If you want to pause code that changes a DOM node or its children, you can use the DOM to change breakpoints.

To set a BREAKpoint for DOM changes:

  1. Click the Elements TAB.
  2. Go to the element where you want to set the breakpoint.
  3. Right-click on the element.
  4. Hover the mouse pointer over Break on, then select Subtree Modifications, Attribute Modifications, or Node Removal.

DOM changes the type of breakpoints

  • Subtree Modifications: Trigger this type of breakpoint when you remove or add a child of a currently selected node, or change the content of a child. This type of breakpoint is not triggered when a child node property changes or any changes are made to the currently selected node.

  • Attributes Modifications: Trigger breakpoints when properties are added or removed from the currently selected node, or when the property value changes.

  • Node Removal: Triggered when a currently selected Node is removed.

XHR/Fetch the breakpoint

You can use XHR breakpoints if you want to break when XHR’s request URL contains the specified string. DevTools pauses on the line where XHR calls send().

Note: This feature can also be used for Fetch requests.

These breakpoints are useful, for example, when you find that your page is requesting the wrong URL, and you want to quickly find the AJAX or Fetch source code that caused the wrong request.

To set an XHR breakpoint:

  1. Click on the Sources TAB.
  2. Expand the XHR Breakpoints pane.
  3. Click Add BreakPoint.
  4. Enter the string on which you want to set a breakpoint. DevTools pauses when the string is displayed anywhere in XHR’s request URL.
  5. According to theEnterKey to confirm.

Event listener breakpoints

If you want to pause event listener code that runs after an event is triggered, you can use an event listener breakpoint. You can select specific events such as Click or event categories such as all mouse events.

  1. Click on the Sources TAB.
  2. Expand the Event Listener Breakpoints pane. DevTools displays a list of event categories such as Animation.
  3. Check one of these categories to pause when any event in that category is triggered, or expand the category and check specific events.

Exception breakpoints

You can use an exception breakpoint if you want to pause a line of code that raises a caught or uncaught exception.

  1. Click on the Sources TAB.
  2. Click on thePause on exceptions

    . When enabled, this button turns blue.

  3. (Optional) If you want to Pause Caught Exceptions when they are raised in addition to uncaught Exceptions, select the Pause On Caught Exceptions check box.

Function breakpoint

If you want to pause while calling a particular function, you can call DEBUG (functionName), where functionName is the function to debug. You can either plug debug() into your code (such as console.log() statements) or call it from the DevTools console. Debug () is equivalent to setting a line breakpoint in the first line of function.

function sum(a, b) {
  let result = a + b; // DevTools pauses on this line.
  return result;
}
debug(sum); // Pass the function object, not a string.
sum();
Copy the code

Make sure the objective function is in range

DevTools raises ReferenceError if the function you want to debug is not in scope.

(function () { function hey() { console.log('hey'); } function yo() { console.log('yo'); } debug(yo); // This works. yo(); }) (); debug(hey); // This doesn't work. hey() is out of scope.Copy the code

If you call Debug () from the DevTools console, it can be difficult to ensure that the target function is in scope. Here’s a strategy:

  1. Sets a line of code breakpoint when the function is in scope.
  2. Trigger this breakpoint.
  3. Called from the DevTools console while the code is still paused at the line breakpoint locationdebug().

Additional debugging tips

When we debug some hover attributes, we often want to adjust the element displayed after the hover, but it will disappear whenever we move to observe the element. This makes debugging very inconvenient. Several scenarios are provided below to give the debugging scheme respectively.

Demo: hua1995116. Making. IO/myblog/exam…

Hover

Simple hover property we just need to find the element that triggered it. Here we have button. So we find our corresponding hover element in Elements. Right click -> force State -> :hover

Mouse inner

If it is triggered by a mouse (mouse event) and the trigger element is written inside the trigger element. You can do this by firing elements at the current time. Right-click -> Break on -> Subtree Modifications. Then trigger again and select skip breakpoint. I can make the element appear.

Mouse outer

The case if it is triggered by a mouse and the trigger element is written outside the trigger element. This can be blocked by a breakpoint trigger. (This method is also compatible with mouser inner cases). Press F8 (Windwos)/Command + \ (Mac) when triggering elements

reference

Developers.google.com/web/tools/c…

Pay more attention

Huayifeng. top/