Category: Browser Tools

  • Browser DevTools Tricks Every Web Developer Should Know

    Browser DevTools Tricks Every Web Developer Should Know

    Here are some actually helpful DevTools techniques you can use daily.

    1. Locate slow paint/layout issues with Performance and Paint Profiler

    • Why: Slow paints and layout thrashing cause jank (stuttered animations, delayed interactions).
    • How:
      1. Open DevTools → Performance (Chrome/Edge) or Performance tab (Firefox).
      2. Click Record, reproduce the interaction (scroll, animate, click), then Stop.
      3. Inspect Main thread: check long tasks (>50ms) and “Layout” / “Paint” events.
      4. In Chrome, open the “Rendering” pane (three-dot → More tools → Rendering) and enable “Paint flashing” to visualize repaints.
    • What to look for: Frequent layout events after small DOM changes, large paint rectangles, long style/layout times.
    • Tips:
      • Temporarily disable heavy CSS (transform/box-shadow) to confirm if paint cost drops.
      • Use will-change sparingly—only for short-lived transitions.
    • Tools: Chrome Performance, Firefox Performance, Lighthouse.
    • Code snippet to avoid layout thrash:
    
    
    
    
    
    js
    // Bad: reading layout in a loop
    items.forEach(el => { el.classList.add('open'); total += el.offsetHeight; });
    // Better: batch DOM reads/writes
    items.forEach(el => el.classList.add('open'));
    let total = items.reduce((sum, el) => sum + el.offsetHeight, 0);
    

    2. Capture exact network conditions and simulate mobile devices

    • Why: Reproduce real-world slow networks and device sizes to catch bugs before users.
    • How:
      1. Network tab → Throttling dropdown → choose presets (Fast 3G, Slow 3G) or Add custom.
      2. Toggle Device Toolbar (Ctrl+Shift+M) to simulate screen size, DPR, and touch.
      3. Use “Offline” to test offline behavior and service worker fallbacks.
    • What to look for: Long time-to-first-byte, large payloads, blocking resources.
    • Tips:
      • Combine throttling with CPU throttling (Performance → CPU throttle) for more realistic tests.
      • Use HAR (Export HAR) to share exact network session details with teammates.
    • Tools: Chrome DevTools, WebPageTest for external runs.
    • Commands:
    
    
    
    
    
    bash
    # Save network log: right-click → Save all as HAR with content
    

    3. Edit and persist CSS on the fly with Workspaces / Overrides

    • Why: Try visual fixes directly in browser and persist them back to disk.
    • How (Chrome Workspaces):
      1. Sources → Filesystem → Add folder to workspace, grant permission.
      2. Map network resource to local file.
      3. Edit CSS/JS in Sources; save (Ctrl+S) writes to disk.
    • How (Overrides, when workspace not possible):
      1. Sources → Overrides → Select folder, grant permission.
      2. Enable “Enable Local Overrides”. Edits to any loaded file get stored locally and reapplied on reload.
    • What to look for: Quick CSS tweaks that require page reload confirmation; map to proper files to avoid confusion.
    • Tips:
      • Keep a git branch for experiments; commit only intentional changes.
      • For React/Vite/etc., use fast refresh but still test final built CSS via overrides.
    • Tools: Chrome Workspaces, Local Overrides, VS Code + live-server for parallel editing.

    4. Debug async code with Async Call Stacks & Blackboxing

    • Why: Understand full call stack across promises and skip libraries that clutter call stacks.
    • How:
      1. Sources → check “Enable async stack traces” (usually on).
      2. Right-click file in Call Stack → Blackbox script (e.g., node_modules) to hide internal frames.
      3. Set breakpoints (conditional, logpoints) and step through async flows.
    • What to look for: Promise microtasks, missing awaits, unhandled rejections.
    • Tips:
      • Use conditional breakpoints to avoid stopping too often (right-click → Add conditional breakpoint).
      • Use console.assert for quick runtime checks without pausing.
    • Code snippet:
    
    
    
    
    
    js
    // Conditional breakpoint example: only break when userId === 42
    if (userId === 42) debugger;
    

    5. Use Snippets for quick automation and repro helpers

    • Why: Automate repetitive inspection tasks (seed test data, toggle features).
    • How:
      1. Sources → Snippets → New snippet.
      2. Save JS code; right-click → Run or run via console with: snippetName().
    • What to look for: Snippets that recreate states hard to reach via UI.
    • Tips:
      • Store commonly used snippets in your workspace and share with team.
    • Example snippet (fill form):
    
    
    
    
    
    js
    (() => {
      document.querySelector('#name').value = 'Test User';
      document.querySelector('#email').value = 'qa@example.com';
    })();
    

    6. Audit accessibility with Accessibility pane and Lighthouse

    • Why: Catch keyboard, contrast, and ARIA issues early.
    • How:
      1. Elements → Accessibility or Audits/ Lighthouse → Accessibility report.
      2. Use “Tab” to navigate and “Focus” overlay to see focusable elements.
      3. Check computed ARIA properties and name/role mappings.
    • What to look for: Missing alt text, low contrast, tabindex misuse, missing labels.
    • Tips:
      • Use axe-core or WAVE for deeper checks; Lighthouse gives actionable fixes.
    • Tools & commands:
      • npm: npm install -g @axe-core/cli && axe page.html
    bash, command-line, linux, shell, terminal, bash, linux, linux, linux, linux, linux, terminal

    7. Live-edit JS pretty-print and map minified code back to source

    • Why: Debug production minified code when source maps aren’t available.
    • How:
      1. Sources → open minified .js → click {} pretty-print to format.
      2. Use “Search” to find likely function names, set breakpoints.
      3. If source maps exist, DevTools will show original files automatically.
    • What to look for: Inline eval’d code, dynamically generated functions, missing maps.
    • Tips:
      • Use sourcemap explorers (sourcemap.spec.whatwg.org) and build tools to ensure maps are generated and uploaded to Sentry or your error tracking.
    • Example: Add source-map support in Webpack:
    
    
    
    
    
    js
    module.exports = { devtool: 'source-map' };
    

    8. Memory leak detection with Allocation instrumentation and Heap snapshots

    • Why: Unbounded memory growth leads to crashes and degraded performance.
    • How:
      1. Performance → Memory or Memory tab (Chrome).
      2. Use “Allocation instrumentation on timeline” and record while reproducing the issue.
      3. Take heap snapshots (Memory → Take snapshot) and compare over time (detached nodes, retained size).
    • What to look for: Detached DOM nodes, large retained trees, closures holding large objects.
    • Tips:
      • Force GC (Collect garbage) before snapshots to reduce noise.
      • Track event listeners: use getEventListeners(elem) in console.
    • Commands/snippets:
    
    
    
    
    
    js
    // Find listeners
    getEventListeners(document.querySelector('#btn'))
    

    9. Edit request/response bodies and replay network requests

    • Why: Test server-edge cases without changing backend code.
    • How:
      1. Network tab → right-click request → Save as HAR.
      2. Use “Replay XHR” (in some DevTools) or copy request as cURL → modify → curl to replay.
      3. Use Request Blocking (Network → Block request URL) to simulate missing resources.
    • What to look for: Error handling, fallback UI, resumable uploads.
    • Tips:
      • Use Postman/Insomnia for complex API replay and mutation.
    • Example: Copy as cURL and tweak:
    
    
    
    
    
    bash
    curl 'https://api.example.com/data' -H 'Authorization: Bearer x' --data '{"bad":"data"}'
    

    10. Time travel with Recorder and Puppeteer/Playwright integration

    • Why: Record flows and replay for debugging or automated regression tests.
    • How:
      1. Chrome Recorder tab → Record user flows → export to Puppeteer/Playwright or replay.
      2. Use exported script in CI to run deterministic flows.
    • What to look for: Flaky selectors, timing-based failures.
    • Tips:
      • Prefer data-test-id selectors to avoid brittle tests.
    • Example (Playwright export snippet):
    
    
    
    
    
    js
    const { test, expect } = require('@playwright/test');
    test('flow', async ({ page }) => {
      await page.goto('https://example.com');
      await page.click('data-test=login');
    });
    

    11. CSS Overview and Coverage to prune unused styles

    • Why: Reduce CSS payload and improve first paint.
    • How:
      1. CSS Overview (three-dot → More tools → CSS Overview) to get bundle breakdown (colors, fonts, unused declarations).
      2. Coverage (three-dot → More tools → Coverage) → Start instrumenting → reload to see unused JS/CSS bytes.
    • What to look for: Large unused CSS blocks, duplicated rules, large fonts.
    • Tips:
      • Use PurgeCSS/Uncss in build pipeline, but validate visually—dynamic classes may be removed.
    • Tooling: PurgeCSS, PurgeCSS + Tailwind config safelisting.

    12. Use Console Utilities and formatters for faster debugging

    • Why: Quickly inspect elements, objects, and run helper utilities.
    • How:
      1. In console, use $0, $1 to reference last inspected elements; $$() for querySelectorAll; $x() for XPath.
      2. console.table(), console.group(), console.time()/timeEnd() for structured logs.
      3. Register custom formatters for complex objects (Chrome DevTools custom formatters).
    • What to look for: Too much noisy logging—use levels and structured output.
    • Tips:
      • Use console.profile()/console.profileEnd() to tie CPU profiles to code runs.
    • Snippets:
    
    
    
    
    
    js
    console.time('render');
    // ... render logic
    console.timeEnd('render');
    console.table([{name:'a',size:10},{name:'b',size:20}]);
    

    13. Traffic inspection and modifying headers with Requestly or DevTools

    • Why: Simulate CORS, auth, or header changes locally.
    • How:
      1. Use browser extension Requestly or ModHeader to change request/response headers.
      2. Or use Chrome DevTools “Network conditions” or a local proxy (mitmproxy) to rewrite headers.
    • What to look for: CORS failures, caching headers, content-security-policy issues.
    • Tips:
      • For secure HTTPS interception, use mitmproxy with proper certificates.
    • Tools: Requestly, ModHeader, mitmproxy, Fiddler.

    14. Trace Rendering with Layers and Paint Profiler

    • Why: Understand which layers are composited and accelerate with GPU.
    • How:
      1. Rendering panel → Show layer borders, Show FPS meter.
      2. Performance recording → View “Layers” tab to inspect which elements made their own layer.
    • What to look for: Too many layers (costly) or missing layers for animating elements (causes repaint).
    • Tips:
      • Use transform: translateZ(0) or will-change to trigger composite layers for animations (test impact first).
    • Note: Excess layers increase memory and GPU cost—balance is key.

    15. Source-map management and verifying production mapping

    • Why: Proper source maps make production debugging feasible and reduce time-to-fix.
    • How:
      1. Ensure build tool generates source maps (devtool: ‘source-map’ or similar).
      2. Upload source maps to error-tracking services (Sentry, Rollbar) and strip sources if needed for privacy.
      3. Verify in Production: open DevTools on production bundle—check “Sources” for original files.
    • What to look for: Missing maps, incorrect paths, inline source maps exposing source code.
    • Tips:
      • Use hidden or obfuscated maps for public bundles; prefer private upload to error tracker.
    • Commands (Webpack):
    
    
    
    
    
    js
    module.exports = { devtool: 'hidden-source-map' };
  • Key differences between Chromium-based DevTools and Firefox DevTools

    Key differences between Chromium-based DevTools and Firefox DevTools

    This is a follow up on our previous firefox post so if you haven’t already read it check here for any questions. That is more of a detailed guide that can be used with chromium browsers as well with the key differences being noted below.

    • CSS Grid & Flexbox visualization
      • Firefox: stronger, more detailed Grid and Flexbox highlighters (interactive overlays, gap/line labels)
      • Chromium: good visualizers but generally less feature-rich for grid diagnostics
    • Layout & box-model UX
      • Firefox: clearer box-model inspector and overlay controls for spacing troubleshooting
      • Chromium: similar capabilities but different UI placement and terminology
    • Performance tooling & profiler UI
      • Firefox: comparable profiling features with different visualizations and emphasis on paint/layout diagnostics
      • Chromium: integrated Lighthouse and early experimental features, flame charts and profiler UX differ
    • Memory tools
      • Firefox: robust heap snapshot and retainers view focused on DOM detachment patterns
      • Chromium: allocation instrumentation and allocation profiler with different workflows for tracking leaks
    • Issues / centralized warnings
      • Firefox: reports many issues via Console and Security panels but lacks identical centralized Issues UI
      • Chromium: built-in Issues panel aggregating CSP, deprecations, mixed content etc
    • Rendering diagnostics (paint/layers)
      • Firefox: paint flashing, layer borders and compositing tools with different visualization strengths
      • Chromium: comparable rendering tools and an FPS meter, implementations and visuals differ
    • Early experimental features
      • Firefox: may lag on some experiments but offers unique UX strengths for CSS/layout.
      • Chromium: often receives experimental DevTools features earlier (and integrates Lighthouse)
    • Framework/extension ecosystem
      • Firefox: supports major framework devtools but fewer third‑party DevTools extensions overall
      • Chromium: broader extension availability (React/Vue tools, Lighthouse extension, many DevTools extensions)
    • Remote debugging UX
      • Firefox: about:debugging for remote devices; comparable but different workflow.
      • Chromium: chrome://inspect for Android and a large ecosystem of remote/debugging tools
    • Default privacy/telemetry posture
      • Firefox: generally more privacy-forward in defaults (affects telemetry and some DevTools integrations)
      • Chromium: more integrations and telemetry options enabled by default in many builds
    • UI/interaction differences (short list)
      • Panels naming: Elements (Chromium) vs. Inspector (Firefox)
      • Device Mode (Chromium) vs. Responsive Design Mode (Firefox): similar features, different controls
      • Console toggling and shortcuts are mostly the same but some keybindings and menu placements differ
    Chromium devtools screenshot

    Using both Chromium based browser and Firefox tools together

    Use both toolchains when diagnosing cross‑browser issues. If you reproduce in both you can catch engine-specific rendering, layout or JS differences.

    For example you can use the Elements/Inspector panels to compare computed styles, box‑model overlays and Grid/Flexbox highlighters to spot layout differences; toggle and edit CSS live in each to see engine‑specific rendering.

    Capture network activity and HARs from both browsers to compare request timing, caching headers, and resource sizes, then run performance recordings (flame charts in Chrome, Performance/paint diagnostics in Firefox) to identify different long‑tasks, layout thrashing or paint costs.

    Take heap snapshots or allocation profiles in each to detect memory leaks that may manifest differently across engines.

    Run accessibility audits (Lighthouse in Chrome and the Accessibility Inspector in Firefox) and validate with a screen reader to surface divergent ARIA or focus issues.

    Finally, reproduce fixes in both browsers and retest in Device/Responsive modes and on real devices via remote debugging (chrome://inspect and about:debugging) to ensure cross‑browser consistency.

    Resources and links

  • Using Firefox to Inspect a Webpage

    Using Firefox to Inspect a Webpage

    Why inspect a page?

    • Debugging: find broken DOM, CSS specificity issues, JS errors
    • Performance: spot slow network requests, heavy scripts, memory leaks
    • Accessibility & SEO: verify semantic markup, ARIA, headings and meta tags
    • Learning & reverse‑engineering: understand layout patterns, CSS tricks and JS behavior
    • Rapid prototyping: live-edit HTML/CSS and test fixes without redeploying

    How to open Developer Tools

    • Keyboard shortcut: F12 or Ctrl+Shift+I (Cmd+Opt+I on macOS)
    • Right‑click any element → Inspect Element
    • Menu: Tools → Web Developer → Web Developer Tools
    • Remote: about:debugging → Connect to device / Firefox instance

    Overview of built‑in DevTools

    • Inspector (Page Inspector)
      • View/edit DOM and CSS rules, computed styles, box model and layout
      • Use: layout bugs, specificity problems, CSS experiments
      • Features: element picker, rule search, style editing, box model overlays, CSS variables preview
    • Box Model & Layout tools
      • Visual margins/padding/border overlays; Grid and Flexbox highlighters
      • Use: debug spacing, alignment, grid gaps
    • Fonts panel
      • See used webfonts, font-face declarations, fallback chain, line-height, weight
      • Use: typography debugging and license checks
    • Animations inspector
      • Timeline for CSS and Web Animations API; scrub, replay, slow motion
      • Use: debug timing and easing, capture frames
    • Web Console
      • Logs, errors, warnings, network messages, DOM exceptions, CSS warnings
      • Execute JS in page context, inspect objects and elements
      • Use: quick evaluation, console.table, saving logs
    • JavaScript Debugger
      • Set breakpoints (line, conditional, XHR/fetch), step through, watch expressions, examine call stack and scopes
      • Use: tracing runtime bugs, async stack traces, break on exceptions
    • Network Monitor
      • Full request/response view, timings (DNS/connect/TLS/TTFB), size, initiator, priority, headers, preview/response body, throttling
      • Use: asset optimization, caching issues, API debugging
    • Performance (Profiler)
      • Record frames, JavaScript CPU usage, paint/layout events, call trees, flame charts
      • Use: find code hotspots, layout thrashing, long tasks causing jank
    • Memory
      • Heap snapshots, allocation stacks, retainers, detect leaks and high memory objects
      • Use: reduce memory bloat, track closures holding DOM
    • Storage / Application panel
      • Inspect cookies, localStorage, sessionStorage, IndexedDB, Cache Storage, service workers
      • Use: debug auth, caching strategies, stale content
    • Responsive Design Mode
      • Emulate device viewports, DPR, touch, UA, and network throttling
      • Use: visual QA across screen sizes and simulated slow connections
    • Accessibility Inspector
      • Accessibility tree, computed name/role/state, contrast checker, ARIA properties
      • Use: compliance checks, screen reader troubleshooting
    • Security
      • TLS/HTTPS status, mixed content, certificate info
      • Use: detect insecure resources and certificate issues
    • Application Security & Permissions
      • Inspect permissions, feature policy, CSP violations in console
    • Performance Tools for Graphics & Layers
      • Paint flashing, layer borders and frame-rate diagnostics for heavy animations

    Tips and tricks

    • Use Ctrl/Cmd+F in Inspector to search HTML/CSS
    • Right‑click a rule → Copy → Copy Rule or Copy Declaration to transfer fixes
    • Use “Toggle Element State” to force :hover/:active/:focus states for testing
    • Pin frequently used panels (three‑dot menu → Settings → Toolbox) to keep your layout
    • Use multi‑selection (Shift/Ctrl) in Console for batch operations
    • Persist logs across reloads (Console “Preserve log”) when debugging redirects or service worker registrations
    • Throttle network to Slow 3G to surface timing bugs and lazy load problems early
    • Use the “Disable Cache” option (Network panel) while DevTools is open to bypass cache during reloads
    • Use pretty-print and source maps in Debugger for minified code
    • Use conditional breakpoints to avoid noisy stepping in loops
    • Use “Break on attribute mutation” or “Break on subtree modifications” in Inspector for dynamic DOM problems
    • Use the “Take screenshot” and “Capture node screenshot” options in the Inspector for image assets or bug reports

    Useful built‑in workflows

    • Audit large page loads: open Network → sort by size/time → identify big assets → compress/serve smaller formats (WebP/AVIF), lazy load images and implement HTTP caching headers
    • Find memory leaks: take two Heap snapshots before/after action, diff the snapshots and inspect retained DOM nodes and detached elements
    • Speed up time‑to‑interactive: record Performance while loading, inspect long tasks and paint/layout recalc events, prioritize code splitting and defer non‑critical work

    Add‑ons and external tools that pair well with Firefox DevTools

    ExtensionAdds / PurposeUse Cases
    Web Developer (by Chris Pederick)Extra toolbar of DOM/CSS utilities (disable styles, outline elements, forms tools)Quick diagnostic actions and mass toggles
    React Developer ToolsInspect React component tree, props, state, hooksDebug React structure and performance; integrates with DevTools profiler
    Vue.js DevtoolsVue component inspector, performanceVue SPA debugging and state inspection
    Redux DevToolsTime‑travel debugging for Redux storesFor Redux-driven apps to replay actions and inspect state
    WappalyzerDetect tech stack, frameworks, libs usedQuick reconnaissance and dependency checks
    Lighthouse (via extension or CLI)Automated performance/accessibility/SEO auditsHigh-level audits and actionable suggestions
    ColorZilla / EyedropperPick colors from the page and create palettesVisual QA and color checks
    HTTP Header Live / Modify HeadersView/modify request headers on the flyTest CORS, security headers, feature detection
    LiveReload / BrowserSync (local dev)Auto-refresh and synced testing across devicesRapid local development iteration
    CSS PeeperRead styles, fonts, assets in a friendly UIFast style extraction for design handoff

    Note: many capabilities (network, console, accessibility) already exist in DevTools. Some extensions mainly add framework-specific inspection, recon tools or UI conveniences

    Accessibility and testing considerations

    • Use the Accessibility Inspector to surface missing labels, roles and improper semantics
    • Use color contrast tool in Accessibility panel. Fix low contrast by adjusting foreground/background or font weight
    • Use keyboard testing (Tab order inspector) to ensure logical focus flow
    • Test with a screen reader (NVDA/VoiceOver) where possible, the Accessibility Inspector helps but should not replace real assistive tech

    Advanced topics & workflows

    • Remote debugging: connect Firefox on Android or another desktop instance via about:debugging → connect and debug pages on the device
    • Source maps & transpiled code: enable source maps in Debugger settings to step through original TypeScript or transpiled code
    • Automating checks: combine Lighthouse, Puppeteer or Playwright tests to run performance/accessibility checks in CI
    • Custom DevTools extensions: build an extension for a bespoke workflow (see “Extending DevTools” in Firefox docs)
    • Network recording for reproducible bug reports: export HAR from Network Monitor to share with teammates

    Common pitfalls and how to avoid them

    • Caching hides changes, use “Disable cache” while DevTools is open
    • Minified code without source maps, enable source maps or generate them in your build
    • Over-reliance on developer mode alone — cross‑check in real devices and browsers

    Resources and Official Docs