Cách Debug Javascript Trên Chrome

This article will focus on debugging JavaScript code within Google Chrome’s Developer Tools. Chrome’s Developer Tools are extremely powerful & will almost certainly tốc độ up your troubleshooting process.

Bạn đang xem: Cách debug javascript trên chrome

We’ll be using nhlhockeyshopuk.com Crash Reporting to lớn find the stachồng trace và the line of code the error occurred on. You can sign up for a free 14-day trial here.

The steps we are going to follow are:

So, let’s dive in!

Step 1: Sample project introduction

To demonstrate how khổng lồ debug an application with Chrome Dev Tools, I’m going khổng lồ use a simple “Add Person” form. This size allows you to enter a first, middle, và last name. On clicking the “Save” button, the form will vị a bit of processing, and the data will be sent off to your (imaginary) hệ thống.

*

The code for this form has three functions:

A clichồng handlerA capitalize string functionA save function

var saveButton = document.getElementById('saveButton');var firstNameField = document.getElementById('firstName');var middleNameField = document.getElementById('middleName');var lastNameField = document.getElementById('lastName');function onSaveButtonClick() var firstName = firstNameField.value; var middleName = middleNameField.value; var lastName = lastNameField.value; // capitalise the names firstName = capitalizeString(firstName); middleName = capitalizeString(middleName); lastName = capitalizeString(lastName); doSave(firstName, middleName, lastName);function capitalizeString(value) return value.split('')<0>.toUpperCase() + value.slice(1);function doSave(firstName, middleName, lastName) alert(firstName + ' ' + middleName + ' ' + lastName + ' has been saved!');saveButton.addEventListener('click', onSaveButtonClick);
Unfortunately, after shipping this to lớn production late on a Friday evening, you start khổng lồ see error reports coming into your dashboard. There’s a bug, and you need to lớn fix it, quickly.

2. Analyze the report in nhlhockeyshopuk.com Crash Reporting

Error reports that come inkhổng lồ nhlhockeyshopuk.com contain plenty of information that you can use khổng lồ find và fix the error, so let’s have a look at what we’re dealing with.

*

The information you will need to debug the error is located in the “Stacktrace” module.The “Message” part of the Stacktrace is a short overview of what is wrong. In this case, the toUpperCase method is being called on an undefined value.

The Stacktrace tells you where the error occurred và the sequence of function calls that led there. As you can see in the screenshot above, the error happened in the capitalizeString function on Line 22 of the index.js tệp tin.

Knowing which line triggered the error means you can jump straight to lớn the place where the error occurred & start digging inkhổng lồ what has caused the problem.

3. Exploring the anatomy of the Developer Tools

The first step is khổng lồ launch the ứng dụng in Chrome and open up the Dev Tools. You can vày this with the keyboard using the shortcut CMD-OPT-I on macOS or CTRL-SHIFT-I on Windows.

The Dev Tools will now be open inside the browser tab, & the Console tab will be active sầu. This tab allows you lớn exeđáng yêu arbitrary JavaScript code at any time or to lớn view any outputs from console.log calls.

Try inputting alert("Hello!"); và hitting Enter. You should see the alert appear straight away.

*

The Console tab is a valuable debugging tool as you can use it as a scratch pad for trying out code & evaluating variables as you diagnose your problem.

To debug the code, you first need to be able to lớn navigate through your source code in the Dev Tools. You vị this in the Sources tab.

*

The left pane of this tab has a tree view of all the source files loaded into lớn the page. You can navigate these as you would in an IDE, as the contents are displayed in the central pane. The bottom pane gives you all your debugging options, which we will discuss in more detail later in the article.

If you have a lot of files, you can search them by using the shortcut CMD-Phường on macOS or CTRL-P on Windows, và then just start typing the name of the file.

In the tiện ích, you know the problem lies in the index.js file, so select it from the menu on the left lớn view its contents.

Step 4: Add breakpoints lớn your code

Now that you know how khổng lồ view your code, we want to lớn be able to lớn step through it a line at a time lớn see where things may have gone wrong. To vì this, we use breakpoints. Breakpoints are markers at specific points in the code which stop execution so you can inspect the state of the code at that point in time, & continue execution line-by-line.

There are a few different ways lớn add breakpoints which I’ll go over here:

Event breakpoints

You can force execution to break when a specific event happens on the page. Using the Event Listener Breakpoints section in the debugging pane, you can expand the relevant group và find the sự kiện you want lớn stop execution after.

For example, you could kiểm tra the box for the “click” sự kiện which will stop execution when a clichồng is made anywhere on the page.

*

Line breakpoints

The most comtháng way lớn add a breakpoint is to lớn find the specific line you want khổng lồ stop on & add it there. Navigate to the tệp tin & line you are interested in and clichồng the line number. A xanh marker will be added on that line và execution will now stop every time it hits that line of code. In the screenshot below it will stop on Line 7 of index.js.

*

Programmatic breakpoint

You can also add breakpoints programmatically, which can be useful if you don’t want to lớn search through your code in Dev Tools when you have it handy in your IDE. You can also use this approach to lớn conditionally introduce breakpoints (for example, at certain iterations of loops, or if the code runs on page load và there’s no time to lớn add the breakpoint manually).

Xem thêm: 9 Kinh Nghiệm Đi Lễ Phủ Tây Hồ, Sắm Lễ Cầu Tài Lộc Năm 2020

To bởi this, you add the debugger; statement at the position you want lớn break the execution. The code below will have the same effect as the Line breakpoint above.

*

Error breakpoint

Dev Tools has a handy feature which will stop execution when it hits an exception in your code, allowing you lớn examine what’s going on at the time of the error. You can even choose to stop on exceptions that are already handled by a try/catch statement.

To enable this feature cliông xã the stop sign icon with the pause symbol within it. It will be xanh when enabled. Check the box that appears lớn also break on caught exceptions.

*

Step 5: Step through your code

Now that we know how to break inlớn our code we now want lớn step through each line so we can figure out what’s going wrong. First, put a breakpoint on Line 7 - just inside the Add button’s click handler so we can start at the beginning.

In the previous section, we inferred from the nhlhockeyshopuk.com error report that the error came from the capitalizeString method. This method is called three times, so which instance is the culprit? You can look a little closer at the Stacktrace and see that it was the Call that came from Line 13 which caused the error. You know that Line 13 relates to the Middle Name value. Therefore, you should focus your effort on reproducing the error by crafting your input correctly.

With this extra knowledge, you can fill in the First và Last Name fields but leave the Middle Name blank khổng lồ see if this triggers the error.

Hit the Save sầu button. From here, the Source tab will open where you can see the breakpoint activated. You can now start to lớn step through the code. To vì chưng this, you use the buttons in the debugging pane. This set of buttons can be used to lớn pause execution, lớn step over the next function hotline, khổng lồ step into lớn the next function call, khổng lồ step out of the current function Điện thoại tư vấn, lớn step forward, lớn deactivate breakpoints altogether, or khổng lồ pause on exceptions.

You’re going khổng lồ use these lớn step all the way lớn your capitalizeString function. So from Line 7, use the “Step over Current Line” button until we get to lớn Line 13. The active sầu line is shown with lines above và below it.

*

You can now use the “Step inkhổng lồ Function” button to move into lớn the điện thoại tư vấn khổng lồ the capitalizeString function, jumping from Line 13 to Line đôi mươi.

*

Navigating the Hotline Stack

When you’re moving through the code like this, you might want to lớn jump back to lớn a parent function to lớn kiểm tra what was happening at that point. To vì chưng this, use the điện thoại tư vấn Staông chồng section, which lists all the functions that have sầu been passed through to get lớn this point in your code — exactly the same as the hotline Stack shown in the nhlhockeyshopuk.com error report.

*

You can simply cliông chồng on an tòa tháp in this danh mục and you will be moved baông chồng to lớn that function. Bear in mind that the current position in the execution doesn’t change, so using the Step Over buttons will continue from the top of the call-staông chồng.

Step 6: Determine the state of your application

Now you’ve navigated lớn where your error happened we need lớn examine the state of the application and figure out what’s causing the error.

There are a bunch of options for figuring out what values variables contain & evaluating expressions before the code moves on. We’ll look at each in turn:

Mouse hover

The simplest way to lớn determine the value of a variable is to just hover the mouse over it and a tooltip will pop up with the value. You can even select a group of expressions và hover over this lớn get the output of the expression.

Watches

You can add expressions lớn the Watch panel which displays the current value of the expression as you move through the code. This is handy to keep traông chồng of how more complex expressions change over time.

You add these by either clicking the “+” button at the top of the panel or by selecting an expression, right-clicking & choosing “Add selected text lớn watches”.

*

Scope

The Scope panel displays a các mục of variables currently within scope và their associated values. This is similar khổng lồ the Watch panel but is generated automatically by Chrome Dev Tools. The Scope panel is good for identifying local variables và saves you explicitly adding them to the Watch menu.

*

Console

Finally, the Console tab is a great tool for checking expression values và experimenting with code. Just switch baông xã lớn the Console tab, type some code & hit enter. Chrome Dev Tools will exeđáng yêu the code within the context & scope of the current breakpoint.

Step 7: Fix the bug

Switch over khổng lồ the Console tab and let’s start khổng lồ break down the line that caused the error so you can fix it using the Console tab.

First, check the output of the value.split("") Hotline so you can get the first character then Call the toUpperCase function on it.

Executing the expression in the Console shows it returns an empty array — this is where the error comes from! Since it returns an empty array and we try to call toUpperCase on the first thành tích (which is undefined, since there are no items) that gives you the error.

You can verify this by entering the full expression into the Console:

*

So, lớn fix the problem, you need to lớn kiểm tra that the string is either empty or undefined. If it is, you need to return an empty string baông xã without doing any processing.