Cool Chrome DevTools Tips and Tricks You Wish You Knew Already

As a full-stack developer, you probably spend a good chunk of your day working in Chrome DevTools. It‘s an indispensable tool for inspecting, debugging, and tweaking web pages. While most developers are familiar with the basics of using the Elements panel to adjust styles or the Console to run JavaScript, DevTools has a ton of other powerful features that can significantly boost your productivity.

In this in-depth guide, we‘ll dive into a selection of cool DevTools tips and techniques that even many experienced developers don‘t know about. Whether you‘re a front-end developer or work across the whole stack, you‘ll find some useful tricks here to level up your DevTools skills. Let‘s jump in!

1. Quick-Access Recent Elements

When inspecting elements on a page, you‘ll often find yourself needing to re-select a previously inspected element. DevTools keeps track of the last five elements you‘ve selected in the Elements panel, and you can quickly access them using the $0, $1, $2, $3, and $4 shortcuts in the Console.

  • $0 references the currently selected element
  • $1 references the previously selected element
  • $2 references the element selected before $1, and so on
$0 // currently selected element
$1 // previously selected element
$2 // element selected before $1

This is really handy when you need to run commands against a specific element multiple times. Instead of having to re-select the element or store it in a variable, you can simply use these quick-access variables.

2. Accessing Elements in the Console

On a related note, there are a few other ways to reference DOM elements from the Console beyond the $0 syntax:

  • $(‘css-selector‘) returns the first element matching the given CSS selector (same as document.querySelector())
  • $$(‘css-selector‘) returns an array of all elements matching the CSS selector (like document.querySelectorAll())
  • $x(‘//xpath‘) returns an array of elements matching the given XPath expression
$(‘h1‘) // first <h1> element
$$(‘p‘) // all <p> elements 
$x(‘//img‘) // all <img> elements

These shorthand utilities are incredibly useful for quickly manipulating elements from the Console. Note that if you‘re using a library like jQuery on the page, the $() function will be overridden to reference jQuery instead, but you can still use $$ and $x.

3. Monitoring Events

If you‘re debugging an issue with events not firing as expected, the monitorEvents() function in the Console is your friend. You can pass it an element to monitor, and it will log information to the Console whenever an event occurs on that element or any of its descendants.

monitorEvents(document.body, ‘click‘);

Monitoring click events on document.body

You can also specify multiple event types to monitor by passing them as additional arguments:

monitorEvents(document.body, [‘click‘, ‘keyup‘]);

When you‘re done monitoring events, simply call unmonitorEvents() with the same element to stop the event logging:

unmonitorEvents(document.body); 

This is a really effective way to track down issues with event handlers not triggering or firing too many times. Rather than having to manually add log statements in your event listeners, you can use monitorEvents() to automatically log all events of a given type.

4. Evaluating Console Expressions on Page Load

By default, expressions you type into the Console will execute in the context of the currently loaded page. But what if you want to run a script as soon as the page loads, before you even open DevTools? You can do this by using the Console Drawer.

To open the Console Drawer, press Esc while DevTools is open, or click the Show Console Drawer button in the top-right corner of the Console panel.

Opening the Console Drawer

With the drawer open, any expressions you type will be executed as soon as the page loads, before other scripts run. This is useful for setting up global variables or overriding functions for debugging purposes.

Executing expressions on page load with the Console Drawer

Keep in mind that scripts executed in the Console Drawer don‘t have access to the page‘s JavaScript scope, since they run before the page scripts. But you can still interact with the DOM and use browser APIs.

5. Styling Console Output

You‘re probably used to using console.log() to print plain-text messages to the Console. But did you know that you can style your log messages with CSS?

The %c directive lets you apply CSS styles to console output by passing a string of CSS rules as the second parameter to any of the console logging functions.

console.log(‘%cHello, world!‘, ‘color: blue; font-size: 24px‘);

Styling console.log output with CSS

You can apply any valid CSS to style your console messages, including backgrounds, gradients, shadows, and animations! This is a great way to make certain logs stand out or categorize different types of output visually.

console.log(‘%cSuccess!‘, ‘color: green; font-weight: bold‘);
console.warn(‘%cWarning!‘, ‘color: orange; text-decoration: underline‘); 
console.error(‘%cError!‘, ‘color: red; background: yellow; padding: 2px 5px; border-radius: 2px‘);

Categorizing log messages with styles

Note that the %c directive only applies CSS styling to the content that comes after it in the log message. To style the entire message, make sure the %c is the first thing in the string.

6. Measuring JavaScript Performance

The Performance panel in Chrome DevTools is an incredibly powerful tool for analyzing your site‘s JavaScript performance and identifying bottlenecks. To start a performance recording, open the Performance panel and click the Record button, or press Ctrl + E.

Chrome DevTools Performance panel

Once the recording has started, perform the actions you want to analyze on the page. DevTools will capture detailed performance metrics the whole time. When you‘re done, stop the recording to view the results.

Viewing performance metrics

The Performance panel can be overwhelming at first glance because it provides so much data. But once you know what to look for, it‘s an invaluable tool for performance debugging. Some key things to pay attention to:

  • The Main section shows an overview of the page‘s activity, broken down into categories like Loading, Scripting, Rendering, and Painting. Look for large blocks of scripting time that could indicate long-running JavaScript tasks.
  • The Timings section shows a graphical view of the page‘s network requests, with a timeline showing when each resource was requested and how long it took to load. Look for resources that are blocking the page load or taking a long time to download.
  • The Call Tree tab shows a breakdown of the JavaScript functions that were called during the recording, organized by which functions called which other functions. This is useful for identifying functions that are taking a long time to execute. You can also switch to the Bottom-Up tab to see which functions took up the most time in aggregate.
  • The Event Log section shows a detailed log of all the events that occurred during the recording, including user interactions, network requests, and JavaScript function calls. This is useful for getting a step-by-step view of what happened during the recording.

One of the most powerful features of the Performance panel is the ability to capture JavaScript stack traces during the recording. To do this, click the Collect JavaScript CPU Profile checkbox before starting the recording.

Enabling JavaScript CPU profiling

With this option enabled, DevTools will capture detailed stack traces showing exactly which JavaScript functions were executing at each point during the recording. You can then view these stack traces in the Samples tab of the Performance panel.

Viewing JavaScript stack traces in the Samples tab

The Samples tab shows a list of JavaScript functions that were called during the recording, organized by the percentage of time each function took up. You can click on a function to view its stack trace and see which other functions it called.

This is incredibly useful for identifying performance bottlenecks caused by long-running or frequently-called JavaScript functions. By looking at the stack traces, you can see exactly which code paths are taking up the most time and focus your optimization efforts accordingly.

7. Identifying Unused JavaScript

Another common cause of JavaScript performance issues is unused code. Over time, as a codebase grows and evolves, it‘s easy for unused functions and libraries to accumulate, adding unnecessary bloat to the page.

Chrome DevTools can help you identify unused JavaScript code with the Coverage tab. To open it, press Ctrl + Shift + P to open the Command Menu, start typing "coverage", and select Show Coverage.

Opening the Coverage tab from the Command Menu

In the Coverage tab, click the Reload button to reload the page and capture coverage data. DevTools will then show you a list of all the JavaScript and CSS files loaded by the page, with a breakdown of how much code in each file is actually being used.

Viewing code coverage data

Unused code will be highlighted in red. You can click on a file to view it in the Sources panel with the unused code highlighted.

This is a great way to identify legacy code or third-party libraries that are no longer needed and can be safely removed to reduce the page‘s JavaScript footprint. Just be careful not to remove code that‘s actually needed for other parts of the site!

8. Debugging Asynchronous Code

Debugging asynchronous JavaScript code can be tricky because it‘s not always clear when or in what order different code paths will execute. Chrome DevTools provides some useful tools for debugging async code, including breakpoints and the Async stacks feature.

To set a breakpoint in an async function, open the Sources panel and navigate to the function in the code tree. Click the line number where you want to add the breakpoint, or right-click and select Add breakpoint.

Setting a breakpoint in an async function

When the breakpoint is hit, execution will pause and you can step through the code as usual. But with async code, the call stack will often be empty because the function was called asynchronously. To see the full async stack trace, click the Async checkbox in the call stack pane.

Viewing the async stack trace

The async stack trace shows the full path of function calls that led to the current breakpoint, even if those calls happened asynchronously. This is really helpful for understanding the flow of complex async code.

You can also use the debugger keyword to pause execution at a specific point in an async function, just like with synchronous code.

async function foo() {
  // ...
  debugger;
  // ...
}

When the debugger statement is hit, execution will pause and you can inspect variables, step through code, and perform other debugging tasks.

9. Debugging Node.js Apps

So far we‘ve focused on debugging JavaScript code in the browser, but what about Node.js apps? Thankfully, Chrome DevTools can also be used to debug Node.js applications using the built-in Inspector protocol.

To enable debugging in a Node.js app, run the app with the --inspect flag:

node --inspect app.js

This will start the app and listen for a debugging client on a specific port (default is 9229). You can then open Chrome and navigate to chrome://inspect to see a list of available Node.js targets.

Inspecting a Node.js app in Chrome DevTools

Click the inspect link next to your app to open a dedicated DevTools instance for debugging the Node.js runtime. You‘ll see the same familiar DevTools UI, but with some Node.js-specific panels like Profiler and Memory.

Debugging a Node.js app with Chrome DevTools

From here, you can use all the same DevTools debugging features we‘ve covered, like breakpoints, step debugging, and performance profiling, to debug your Node.js app. You can even use the console.log() and other logging functions to output messages to the DevTools Console.

One neat feature of the Node.js inspector is that it supports remote debugging over a network. This means you can run your Node.js app on one machine (like a server) and debug it from another machine (like your laptop) using Chrome DevTools.

To do this, start your Node.js app with the --inspect flag and the host and port options to specify which network interface and port to listen on:

node --inspect=192.168.1.100:9229 app.js

Then on your local machine, open Chrome and navigate to chrome://inspect. You should see your remote Node.js app listed under Remote Target. Click inspect to start debugging!

This can be really useful for debugging Node.js apps running in a production or staging environment, without having to SSH into the server and debug locally.

10. Bonus: DevTools Extensions

Finally, it‘s worth mentioning that Chrome DevTools is extensible via a rich extensions API. There are tons of great third-party DevTools extensions that add new features and functionality to the built-in tooling.

Some of my favorites:

  • React Developer Tools – Adds a new "React" tab to DevTools for inspecting React component hierarchies and state.
  • Redux DevTools – Adds a new "Redux" tab for inspecting Redux store state and time-travel debugging.
  • Vue.js devtools – Adds a new "Vue" tab for inspecting Vue.js component hierarchies and state.
  • Lighthouse – Automated tool for auditing web page performance, accessibility, and best practices.
  • Web Vitals – Adds an overlay to the page showing real-time metrics for key web vitals like Largest Contentful Paint (LCP) and Cumulative Layout Shift (CLS)
  • VisBug – Design debug tools for inspecting and tweaking page layouts and styles.

To install a DevTools extension, just search for it in the Chrome Web Store and click "Add to Chrome". The extension will then be available in DevTools under the relevant panel or tab.

Some popular DevTools extensions

There are hundreds of other great DevTools extensions out there, so it‘s worth exploring the Chrome Web Store to see what else is available. And if you can‘t find an extension that does what you need, you can always build your own!

Conclusion

As you can see, Chrome DevTools is an incredibly powerful and feature-rich tool for debugging and optimizing web apps. While it can seem overwhelming at first, taking the time to learn the ins and outs of DevTools will pay dividends in your productivity and effectiveness as a web developer.

In this article, we‘ve covered a ton of ground, from basic element inspection and console logging to advanced performance profiling and Node.js debugging. But we‘ve still only scratched the surface of what DevTools can do. I encourage you to continue exploring and experimenting with DevTools on your own projects, and see what other useful techniques you can uncover.

Happy debugging!

Similar Posts