Interacting with JavaScript using Chrome DevTools
There is a set of utilities included in the Chrome browser (https://developer.chrome.com/docs/devtools/overview/) defined as follows:
All Chrome-based browsers have Chrome DevTools, so you can use it with any browser based on Chromium, such as Google Chrome, Microsoft Edge, Brave, and so on.
The Node.js REPL is very useful, but in order to build web applications with Node.js, we can use Chrome DevTools for debug purposes. This debugging will be limited to client-side JavaScript as the Node.js code is not executed directly in the browser.
Chrome DevTools is a very complete tool, so this can be quite overwhelming at first, but we will focus on the most important features for this book: the Console and Network panels.
The Console panel
The Console panel is the primary way to interact with the JavaScript on the website. The console is interactive so we can write JavaScript code and it will be executed immediately; we can also read the console output.
The following video provides a great overview of the tool: https://www.youtube.com/watch?v=76U0gtuV9AY.
You can read the official documentation here: https://developer.chrome.com/docs/devtools/console/.
The Network panel
The Network panel is very powerful. It allows us to inspect HTTP requests and responses so we can see the headers, body, status code, and so on. This will be very useful when we need to debug any kind of web application. You can find a great tutorial at https://www.youtube.com/watch?v=e1gAyQuIFQo.
You can read the official documentation here: https://developer.chrome.com/docs/devtools/network/.
Using Chrome DevTools
In our case, we will start from an empty website. We will use the Console panel to write JavaScript code that will change the page, and then we will inspect the HTTP requests. Follow these steps:
- In your browser, go to
about:blank
; by default, this will show a blank page. - Open DevTools by right-clicking on the page and clicking Inspect.
- Go to the Console tab and type
document.body.innerHTML = '<h1>Hello World!</h1>'
and press Enter.
Figure 2.1 – Web browser screenshot
- Now, you should see the Hello World! text on the page.
Figure 2.2 – Web browser screenshot with Hello World! text
- Go to the Network tab and navigate to https://packt.com. You should see a lot of activity.
Figure 2.3 – Web browser activity
This was a simple example for you to get familiar with the Chrome DevTools, but you can do much more with it. I recommend you read the official documentation to learn more.