Chrome DevTools is so powerful that it can even replace ides!
- Art of debugging with Chrome DevTools
- Translator: Fundebug
To ensure readability, free translation rather than literal translation is used in this paper. In addition, the copyright of this article belongs to the original author, and translation is for study only.
Fundebug focuses on JavaScript, wechat applets, wechat games, Node.js and Java online bug monitoring in real time. Really a good bug monitoring service, many big companies are using.
Google Developer Tools provides a number of features to help developers Debug web applications efficiently, allowing them to find and fix bugs faster. There are a lot of useful gadgets in Google’s developer tools that most developers don’t know about. In this article, I’m going to share some of my favorite features of the efficient Debug Chrome developer tools.
For brevity, I’m going to use developer Tools to refer to Google Developer Tools.
Before we start, you need to do some preparatory work.
Use the Canary edition
If you want to use the latest version of Google and developer tools, you can download the Canary version and even set it as the developer’s default browser. The Canary edition is designed to provide the latest updates to early adopters. It may be unstable, but most of the time it works. Get used to using the latest and greatest Browser.
1. Enable experimental features of developer tools
You can go to Chrome :// Flags and start Developer Tools Experiments.
When enabled, there is an added Experiments option on the Developer tool Settings page. If you don’t see some of the features I’m using, go to Experiments and open them.
2. Super experimental
If the feature I’m using isn’t on the Experiments list, it’s probably a WIP feature. You can start it like this: On Experiments, press Shift 6 times to activate WIP.
Console
When debugging, we spend most of our time with Console. We tend to insert many Console logs into our code and debug by printing variable values. Given how important Console is to us, it’s important to understand the APIs and shortcuts that all developer tools provide.
3. Always print objects
My first piece of advice has nothing to do with developer tools, but is a technique I use all the time. In the use of the console. The log (); Instead of just printing variables, print objects with curly braces ({}) around the variables. This has the advantage of printing not only the value of the variable, but also the variable name.
4. Use console.table to print multiple entries
If the variable you are printing is an array, each element is an object. I recommend that you use console.table for printing, the tabular rendering is nicer and easier to read.
Add color to the log
Logs can sometimes become very large, including your own logs, some third-party extensions, or browser logs. In addition to using filters, you can also use colors to better differentiate.
6. $ 和 ?
If you don’t have any libraries under Console using $and? Respectively, then you can use them as a document. The querySelector () and the document. The querySelectorAll () of shortcuts.
Besides providing a faster way, there is another advantage,? Return an array instead of array-like NodeList. So you can use map, Reduce and filter functions directly.
Can you use? Check for invalid links in pages:
Promise .all( ? ('a') .map(link => link.href) .map(href => fetch(href)) ) .then(() => console.log('All links working')) .catch(() => console.error('Some links are broken'));Copy the code
7. $0
If you want to reference a DOM element, use $0. $0 refers to the Element you currently select in Element. If $0 is specified, $1 points to the previously selected element. And so on up to $4.
8. $_
$_ records the last expression evaluated on the Console.
9. getEventListeners()
GetEventListeners (domElement) return all events registered on the DOM element. Look at the following example:
You may have noticed that when I type the expression in console, the result is immediately computed. You can see that I didn’t hit Enter, and the result is already there. This is a new feature in Canary called Eager Evaluation.
10. debug(fn)
In the example above, you can use the debug function if you want to pause during execution after clicking the button. Debug (FN) takes a function as an argument and breaks execution on the first line of the function each time the function is called.
Imagine you want to debug a button, but you don’t know where the button’s event function is in your code. There’s another clever way to do this, besides digging through a lot of source code. Use the getEventListeners function and inject the Debug method into it. This way, when you click the button, it will stop on the first line of the function.
11. copy(obj)
Copy (anything) is a useful tool for copying anything to your system’s sticky pad for temporary storage.
Passing an unformatted JSON to copy returns the formatted result:
12. Top-level await
Async /await makes asynchronous operations easier and more readable. The only problem is that await needs to be used in async functions. If we want to use it in the DevTools console, we need to do something special, using the Immediately Invoked Async Function Expression (IIAFE). It’s not convenient at all. Fortunately, DevTools already supports using await directly.
Debugging in the Sources panel
In the Source panel, use breakpoints, stepping-into, stepping-over, etc., you have a good handle on the execution state of the program to find code problems. I’m not going to cover the basics you all know, but some tips and techniques I use frequently.
13. Enable Auto-Pretty Print
In The Canary version of the experimental mode, you can turn on the automatic beautification code mode.
14. Use conditional breakpoints to inject console logs in production
Breakpoints are a great feature. But there’s something even better: conditional breakpoints. The interrupt is executed only when the set condition is met. This means that DevTools doesn’t interrupt your program every time, but only when you want it to. For more: Check it out here.
In a production environment, I like to use conditional breakpoints to inject console.log because I can’t modify the source code. If my breakpoint was just a console.log, DevTools would not break because console.log returns undefined, which is a false value. But it will execute the expression I injected, and you can see the output.
Why not just use regular breakpoints and look at variables? Sometimes I don’t want to do that. For example, when I’m analyzing actions that are frequently performed, such as touch or swipe. I don’t want to cause the Debugger to trigger an interrupt every time, but I want to see the output of the program.
Pause the DISPLAY result of UI in Hover state
It is difficult to examine an element that is only displayed in Hover state. For example, how do I check a tooltip? If you right-click and select Check, the element is gone. So is there a way?
Here’s how I did it:
- Open the Sources panel
- Show tooltip
- Use shortcut keys to pause script execution (hover the mouse over the pause icon to see the shortcut keys)
- Go back to the Elements panel and examine the Elements as usual
16. XHR breakpoints
To understand how a request is executed, use XHR BreakPoints in the Sources panel.
17. Use DevTools as the IDE
DevTools’ Source panel is pretty powerful. You can search quickly, jump to a line, a function, execute a piece of code, use a multi-line cursor, and so on. These features are described in detail in this Medium article.
In that case, why not move the entire development here. There is no need to waste time switching between the IDE and the browser.
If you have a project built using create-react-app or vue-CLI, you can drag the entire folder directly under the Sources panel. DevTools automatically maps all files. So, you can modify the file in DevTools and view it immediately. In this way, the overall development efficiency, especially the Debugging efficiency, is definitely improved.
18. Use Network overrides to simply debug production code
If you are Debugging a bug in a production environment, you can use network Overrides to do the Debugging instead of having to build the entire configuration locally.
You can easily download a local version of any remote resource, edit it in DevTools, and DevTools will update and display your edited file.
Debugging is also easy in a production environment, and it is also easy to do some performance testing.
19. Nodejs debugging
If you want to use the DevTools Debugger to debug node.js applications, you can use –inspect-brk flag to enable it:
node --inspect-brk script.js
Copy the code
Jump to the Chrome ://inspect page and see the Node application under the Remote Target option.
Also, in DevTools you will see a green Node icon, which will open the Chrome Debugger for Node.
If you want to use the DevTools Debugger to debug your unit tests, you need to call:
node --inspect-brk ./node_modules/.bin/jest
Copy the code
However, this is actually very troublesome, we need to find the corresponding path. GoogleChromeLabs recently released a new tool which is very useful, called NDB. To use NDB, you just need:
ndb npx jest
Copy the code
If you have a custom script, you can call it like this:
ndb npm run unit
Copy the code
Even better, if you call NDB in a project that has package.json configured, it will even automatically analyze the script in package.json, making it easy for you to use DevTools directly.
20. Use Snippets to aid Debugging
DevTools provides a tool for creating and saving small pieces of code, and I love using them to speed up my work. Like Lodashify — you can quickly add LoDash to any application.
(function () { 'use strict'; var element = document.createElement('script'); Element. The SRC = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"; element.type = "text/javascript"; document.head.appendChild(element); }) ();Copy the code
Another small utility function that enhances an object’s properties gives me plenty of information about who accessed it and who changed it every time it was accessed or modified. This is very useful in Debugging.
const traceProperty = (object, property) => { let value = object[property]; Object.defineProperty(object, property, { get () { console.trace(`${property} requested`); return value; }, set (newValue) { console.trace(`setting ${property} to `, newValue); value = newValue; }})};Copy the code
There are also many very useful Snippets of DevTools code that you can use directly.
About Fundebug
Fundebug focuses on JavaScript, wechat applets, wechat mini games, Alipay applets, React Native, Node.js and Java real-time BUG monitoring. Since its launch on November 11, 2016, Fundebug has handled more than 600 million error events in total, which has been recognized by many well-known users such as Google, 360 and Kingsoft software. Welcome free trial!
Are your users experiencing bugs?
Experience the Demo
Free to use