The background,

As a front-end engineer, no matter in the development or online environment, browser or Node, mobile terminal or PC terminal, I often encounter some bugs, so how to quickly locate and solve the problems, the author prepared a front-end debugging guide for your reference.

Article outline:

Debugging itself can be divided into two processes, locating problems and resolving them. More important, of course, is how to quickly locate the problem. This article will focus on how to quickly find and debug problems, but how to solve problems is a matter of development itself.

Second, the debugging tool method

2.1 Use of Chrome DevTools

DevTools is one of the most commonly used debugging tools in Chrome. Here are three panels: Elements, Console, and Source.

2.1.1 Elements

Elements panel displays the status of THE DOM and CSS in the current web page, and you can modify the DOM and CSS on the page to see the results in real time, eliminating the need to modify, save and view the results in the editor.

Elements can be divided into two subpanels: THE DOM structure and the Element content

$n

When the Elements panel is opened, there is always a == $0 after the element marked

If you select an element and type $0 in the Console panel, you’ll see that the element you just selected appears in the Console. If you have more elements, you can use $1, $2, $3, $4 (so far) to retrieve the elements you selected earlier.

In addition, right-click an element in the Console and select Reveal in Elements Panel to jump to its location in the Elements Panel. Right-click on Elements in the Elements panel and Scroll to View to see the Elements.

$0 is handy when you want to manipulate elements with JavaScript in the Console panel, and you can also use console.dir($0) to view elements’ attributes. If you type $0 or console.log($0) directly into Console, only the element itself is displayed.

inspect

Sometimes dom nodes are so deeply nested that it’s hard to find them using the Element panel HTML code. Inspect (DOM element) allows us to quickly jump to the HTML code of the corresponding DOM node. Eg: Type inspect($(‘#app’)) on the console and press Enter to jump to the HTML of the #app node to examine the elements

2.1.2 the Console

The Console panel acts as a shell prompt window for interacting with page documents and DevTools

The console object

When it comes to debugging, the most commonly used method is console.log, but console is an object, and it has very handy methods.

Console.table () can be used to print obJ/ARR tables

Console.trace () can be used for debugger stack debugging to see the execution logic of the code and also to see the source code for some libraries

Console. count prints how many times the tag has been executed. The default value is default, which can be used for quick counting.

Console. countReset is generated with count and is used to reset the count that can be used to calculate the trigger of a single action.

console.group() / console.groupEnd();

This is often done in order to see your log at a glance in a jumble of messages

console.log("----start-----");
console.log(object);
console.log("---end---");
Copy the code

It’s obvious, but there’s a better way to use console.group to customize the tag of a Message group or multi-layer nesting and close the group with console.groupEnd

console.log("iteration");
for (var firstLevel = 0; firstLevel < 2; firstLevel++) {
  console.group("First level: ", firstLevel);
  for (var secondLevel = 0; secondLevel < 2; secondLevel++) {
    console.group("Second level: ", secondLevel);
    for (var thirdLevel = 0; thirdLevel < 2; thirdLevel++) {
      console.log("This is third level number: ", thirdLevel);
    }
    console.groupEnd();
  }
  console.groupEnd();
}
Copy the code

The $$(select) method

$(select) gets NodeList(pseudo-array), and $$(select) gets a pure array, which is easy to debug on the console API, and can only be used under DevTools print

2.1.3 Source

The Sources panel allows you to view the source files in the browser page (HTML /js/img/ CSS, etc.). Click the {} curly braces at the bottom of the panel to convert the code to a readable format and add breakpoints to the JS file. Snippets in Sources can add file Snippets that run in the browser

Breakpoints

The debugger statement

After console.log, adding debugger statements to your code is a common way of debugging, adding breakpoints where needed

Chrome devTool breakPoint provides a list of breakpoint methods that are commonly used

  • Normal breakpoint: A single click to the left of the line you want to break adds a breakpoint, and runs there to break.

  • Conditional breakpoints: Right-click on the line to the left of the code, and a drop-down box appears to add a conditional breakpoint. Enter the conditional expression, which breaks when the line is run and the value of the expression is true.

  • DOM breakpoints: Right-click on Elements in the Chrome Devtools Elements panel and select Break on to add a DOM breakpoint, which breaks when a subtree changes, an attribute changes, or a node is removed. Can be used to debug code that causes dom changes.

  • On the Elements panel of Chrome Devtools, find the DOM nodes you want to check for, and the events on the right panel will show the current level of the DOM nodes.

  • Breakpoints: Check Uncaught Exceptions and Caught Exceptions in the Debugger panel to add breakpoints that will break if thrown Exceptions are not Caught or Caught. Useful for debugging code where exceptions occur.

  • Event Listener breakpoint: You can also add an Event Listener breakpoint in the Sources pane of Chrome Devtools, specifying that the Event Listener is broken when an Event occurs, which can be used to debug event-related code. Such as drag events, media event breakpoints

  • Function is available in the Console paneldebugEquivalent to inserting in the first line of the functiondebugger:
function a() {
  console.log(1);
}
// Enter in Console
debug(a);
a();

/ / equivalent to
function a() {
  debugger;
  console.log(1);
}
// Remove using undebug
Copy the code
BlackBox

“BlackBox Script” allows you to ignore scripts during debugging (where BlackBox is a verb), hide them from the Call Stack, and step through without stepping into any of the functions in the Script. If you are sure there are no bugs in the third-party library, you can BlackBox the entire js script of the third-party library and skip the execution of this code during debugging.

Three ways to add a BlackBox:

  1. Right click on the source pane and select “BlackBox Script”
  2. Right click on a frame in the Call Stack and select “BlackBox Script”
  3. Add the regular expression match file name to the Blackboxing panel in Settings
Workspace
In chromeDebug using local sourceMap

Step 1: Open Filesystem Add Folder to Workspace and add the directory containing sourceMap to it

Step 2: Open the specified obfuscation code

Step 3: Right-click -> Select Add Source Map

Step 4: Copy the sourceMap address in the Filesystem.

Modify code and debug in Chrome

Chrome devTools provides local overrides. First, open the Overrides panel under Sources.

Then, click select Folder for Overrides to select the modified file storage address.

Then, click the authorization icon at the top to confirm consent.

Finally, right-click the entry file, and select Save for Overrides.

Then find the saved file and modify it. After refreshing the page, the modified code can be executed.

2.2 nodejs debugging

Nodejs debugs using Chrome DevTools –inspect-brk

The following uses debugging Webpack source code as an example:

node --inspect --inspect-brk node_modules/webpack/bin/webpack.js --env.production --config webpack-common.js
Copy the code

Open chrome’s Developer Tools page by executing the corresponding startup file webpack.js in bin. If you see the green icon of Node, click to debug.

2.3 Debugging VConsole and ErUDA on mobile Devices

Whistle, together with VConsole or ERUDA, can start the debugging mode in any environment. The corresponding domain name can be configured in the rules of Whistle for debugging. Take m.zhuanzhuan.com as an example

m.zhuanzhuan.com jsAppend://{eruda.js} jsAppend://{erudaInit.js}
Copy the code

Download eruda.js and configure erudainit. js in values

This will enable debug ERuda mode on mobile.

2.4 wechat WebView debugging

Wechat debug web pages, normally you can use wechat developer tools to debug web pages and wechat on the computer side. When this situation cannot be met and you need to troubleshoot problems on the real phone, you need to use TBS Studio developed by Tencent X5 for debugging. It is essentially similar to the Chrome ://inspect method, except that it provides debug mode for online wechat packages and simplifies operations. The use of specific methods can refer to the official document: x5.tencent.com/tbs/guide/d…

2.5 Android Chrome real machine Debugging

If you need to debug Android phone version >= 4.4, it is recommended to use Chrome ://inspect for debugging, which brings native developer tools to WebView and makes it easy to debug code breakpoints. This method can be used only if it meets the following three conditions:

  1. The Android 4.4 +

  2. Enable USB connection for device debugging on mobile phone

  3. Enable the WebView debug mode on the client

// Enable the webView debug mode
webview.setWebContentsDebuggingEnabled(true);
Copy the code

When the above requirements are met, visit Chrome ://inspect and the page will display a list of webViews that have debugging enabled on your device. To start debugging, click Inspect under the WebView you want to debug. Use developer tools like remote browser tabs.

2.6 iOS Safari Debugging

If you have DEBUG apps installed on your phone, it is recommended to use Safari, which brings native developer tools to WebViews and makes it easy to DEBUG code with breakpoints. This method can be used only if it meets the following three conditions:

  1. Mac: Safari -> Preferences -> Advanced -> Show “Development” menu in the menu bar check
  2. IOS: Settings -> Safari -> Advanced -> Web Inspector opens
  3. The most important thing is that the App must be in DEBUG mode

Due to the signature verification mechanism of iOS, Safari Debug is not allowed in the real machine official package. Therefore, the package installed on the real machine must be the package with the test signature. We need to contact the client to write the ID of our iOS device into the list of trusted devices, and then use iTunes to install the test package provided by the client. When the above requirements are met, you can view the device and the web page in the WebView in Safari -> development. After clicking on the Inspector, you can open the corresponding page for breakpoint debugging.

2.7 vein as debugging

If the above methods are unavailable due to the system version or the debug mode is not enabled, use weinre. Weinre sends all of the page’s behavior to the service by inserting a script into the page. First we need to install and start the service:

npm install -g weinre
weinre --httpPort 8000
Copy the code

Visit http://localhost:8000 and insert the debug script into the page as prompted. After visiting the page, you will find the corresponding request record appears in the Winere page. Click this record to jump to the following page. This is a web version of the developer tool, you can easily view network requests, console execution code and style changes, etc.

Summary of debugging methods

way advantages disadvantages Recommended scenario
Mobile network Agent + Whistle Local agent 1. Convenient development environment 1. Breakpoint debugging is not possible 1. Recommended use in development environment
Whistle External tool injection (vconsole.js or eruda.js) 1, convenient 2. Breakpoint debugging is not possible 1. Any environment debugging is recommended
Android real machine debugging 1, the closest to the real environment, you can debug breakpoints 1, harsh conditions trouble;

2. Android only;

3. Not convenient enough
1, is to find the guarantee means of the problem
IOS Safari real machine debugging 1, the closest to the real environment, you can debug breakpoints 1, harsh conditions trouble;

2. Ios only;

3. Not convenient enough
1, is to find the guarantee means of the problem
Wechat developer tool debugging 1, can be PC as convenient breakpoint debugging 1. Wechat only;

2. Add your account to the developer account in advance
1. Any scenario that requires the use of wechat
weinre(web inspector remote) 1. Inheritance in whistle is convenient;

2, convenient debugging style, selected to get
1. Breakpoint debugging is not possible 1. Any scenario that requires debugging styles

Iv. General steps of debugging

When exceptions occur, you can quickly locate faults by following the troubleshooting logic.

4.1 Checking whether console errors are reported

You can quickly determine why a page does not conform to expectations

  • What kind of mistake
  • Whether the current page needs to request data

4.2 What is the error

  • Security error: Resolve with the back end
  • SyntaxError/ReferenceError/TypeError: compile phase generally not miss too low-level clerical error, can think of this kind of mistake is write wrong, generally it is easy to find, find the error stack to solve
  • Errors caused by data not conforming to expectations (TypeError, etc.) : Access to nonexistent properties is obtainedundefined/null/NaNAfter equivalence, subsequent exceptions are thrown. Start by examining the data.

4.3 Whether to obtain Data on the Current page

Network requests are one of the volatile factors that can cause unexpected complexity, and checking network requests and data when problems occur is a high priority.

4.4. Check whether the network request is sent successfully

Check the developer tool Network/ Network panel to check whether the interface to obtain data successfully obtains data.

There are two kinds of reasons for not getting data, one is the responsibility in the front end, one is the back end. It is mainly judged from two aspects: whether the content submitted by the request is legal and whether the content returned by the interface meets the expectation.

Key points to view:

  • Is the method correct?
  • Is the URL correct
  • Cross domain
  • The content-Type of the request is correct
  • Whether the requested physique meets the requirements (JSON/Form)
  • Whether they carry identification information

If a valid request does not return as expected, it is resolved by the backend. If the request does not meet expectations, the code is incorrectly written.

  • 500 and other exceptions that shouldn’t occur: 500 is probably a backend problem
  • Write wrong 404 urls
  • Permission problem: Check the identity information carried in the request packet

4.5 Locate where the code should be executed (probably)

If the console has an error message, use Sourcemap to quickly locate the line where the problem occurred. If no error message is displayed, you need to determine the fault area based on the status of the current page and rectify the fault according to the sequence of code execution. This step can be used by more means, the situation is more complex, need specific analysis.

To view the code running status:

  • Check the code in the expected order of execution
  • Check that the data required for rendering is the same as expected

4.6 Check the code in the expected execution order

Use breakpoints, logs, and other means to determine whether the program is executing in the order you want.

4.7 Check whether the data required for rendering is the same as expected

Check whether the data changes at each step are the same as expected.

4.8 General analysis methods of abnormal codes

  • Code annotation uses dichotomy to comment code line by line until the problem is located
  • Class library exception, compatibility problemThis scenario is also common, and we need to debug page exceptions in a way such asSafari.Whistle.vConsoleCheck the exception log to quickly locate the class library for replacement or compatibility solutions.
  • try catchIf your project does not have exception monitoring, look for suspicious code snippetsTry Catch.
  • ES6 syntax compatibilityWe usually passBabelTo compile theES6, but additional third-party libraries with incompatible syntax can cause exceptions on lower-version mobile devices. So, use the debugging method described above, identify exceptions, and then add Polyfill for compatibility

Five, the summary

This concludes the debugging approach for the entire article. Maybe there are a lot of places not in place, professional words are not rigorous, I hope readers and I exchange. I am very happy to give my debugging summary to the front end people benefit.