Sub topic 2
Using Browser Developer Tools to Diagnose Web Pages
Assume basic HTML, CSS, JavaScript, HTTP, and browser page loading. Chromium-based browsers use the panel names below. Firefox and Safari provide similar tools.
Using the Console
Open DevTools with F12 or Ctrl+Shift+I (Cmd+Option+I on macOS), then select Console. The Console evaluates JavaScript in the current page and displays logs, warnings, errors, and stack traces.
Use severity levels to make output useful:
console.log('plain message');
console.warn('something looks off');
console.error('something failed');
console.table([
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' }
]);
console.group('Request details');
console.log('method: GET');
console.log('status: 200');
console.groupEnd();Console Utilities connect the Console to other DevTools features. $0 refers to the element currently selected in Elements. $$('img') returns matching elements as an array. copy(value) copies a value to the clipboard.
$0.classList.toggle('hidden');
$$('img').length;
copy($0.outerHTML);Debugging JavaScript with Breakpoints
A breakpoint pauses execution before a suspicious line. In Sources, click a line number to add one. When execution pauses, inspect local variables, the call stack, and the current scope. Use step over to run the next line without entering a called function, and step into to enter it.
A temporary debugger statement creates a breakpoint when DevTools is open:
function applyDiscount(price, percent) {
const discount = price * percent / 100;
debugger;
return price - discount;
}
applyDiscount(80, 25);Check the value of discount and the callers in the call stack. This often reveals whether the bug is in the calculation or in the input passed to it.
Reading the Network Panel
Select Network, reload the page, and reproduce the action. Each row represents a request. Inspect its status, duration, size, initiator, and response. Filter by Fetch/XHR, JS, CSS, or Img to reduce noise.
A request that is slow may be waiting for the server, downloading a large response, or blocked by another resource. A 404 indicates a missing resource. A 500 indicates a server-side failure. The Timing section separates connection, waiting, and download phases.
Exercise
Which panel should you open first when a button click sends a request that returns status 500?
Show answer
Use Sources to inspect the click handler, then Network to inspect the request and response. The 500 indicates a server-side failure.