Setting JavaScript breakpoints in Chrome can be done as follows:
-
Open Developer Tools: To set a breakpoint, open Chrome's Developer Tools. This can be done in several ways:
- Right-click on page elements and select "Inspect".
- Use the keyboard shortcuts
F12orCtrl+Shift+I(Windows/Linux) orCmd+Opt+I(macOS).
-
Navigate to the Source Code: After opening Developer Tools, click the "Sources" tab. This will display all loaded resources, including JavaScript files.
-
Locate the JavaScript File: On the left side of the "Sources" panel, you'll see a file resource tree. Navigate through this tree to find the JavaScript file you want to debug. Clicking the file will open it in the editor on the right.
-
Set a Breakpoint: In the editor, set a breakpoint by clicking the left edge of the line number. Clicking will place a blue or red breakpoint indicator on that line.
-
Trigger the Breakpoint: Once the breakpoint is set, the execution will pause when the browser reaches that line. At this point, you can inspect variable values and step through the code in the "Sources" panel.
-
Additional Breakpoint Types:
- Conditional Breakpoint: Set a conditional breakpoint by right-clicking the line number and selecting "Add conditional breakpoint", then entering an expression. The code will pause only when the expression evaluates to true.
- DOM Breakpoint: To detect when a DOM element is modified, right-click the element in the "Elements" panel and select "Break on", then choose the appropriate condition, such as changes to child elements.
- XHR Breakpoint: To pause when a specific XMLHttpRequest is made, add a breakpoint in the "XHR/Fetch Breakpoints" section of the "Sources" panel, and enter part or all of the URL.
-
Manage Breakpoints: You can view all breakpoints on the right side of the "Sources" panel. This breakpoint list allows you to enable or disable breakpoints, or remove them entirely.
Here is a simple example demonstrating how to set a breakpoint:
Suppose we have a script.js file containing a simple function:
javascriptfunction sayHello() { console.log('Hello, world!'); }
To set a breakpoint on the console.log statement, open script.js in the "Sources" panel and click next to the line number for that line. When the sayHello() function is called, the execution will pause before the console.log statement, allowing you to inspect the code state.