User Agents

Web browsers and everyday web tech, explained

Chrome DevTools Protocol Screenshots: How-To

· 4 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Taking screenshots via the Chrome DevTools Protocol (CDP) gives you pixel-perfect captures of any page, including full-page scrolls, without needing a browser extension or manual clicks. This works by sending a simple command to a running Chrome instance through WebSocket. You'll need Node.js (or any language with WebSocket support) and a basic understanding of command-line tools.

What You'll Need

  • Google Chrome or Chromium browser installed
  • Node.js (v14 or later) for the example scripts
  • Basic familiarity with the terminal/command prompt

Step-by-Step

  1. Launch Chrome with remote debugging enabled. Close all Chrome instances, then open a terminal and run:
    chrome --remote-debugging-port=9222
    On Windows, use the full path to chrome.exe, e.g., "C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222. On macOS, use open -a "Google Chrome" --args --remote-debugging-port=9222.
  2. Verify the debugging endpoint is active. Open a browser and go to http://localhost:9222/json. You should see a JSON list of open tabs. If you see an error, the port is blocked or Chrome didn't start with the flag.
  3. Get the WebSocket URL for the page you want to capture. From the JSON list, copy the webSocketDebuggerUrl value for the tab you're interested in. If you want to capture a new page, first navigate to it in that tab, then copy the URL.
  4. Install a WebSocket client in Node.js. In an empty folder, run:
    npm init -y
    npm install ws
  5. Write a script to capture a screenshot. Create a file named shot.js with the following content (replace the WebSocket URL with yours):
    const WebSocket = require('ws');
    const fs = require('fs');
    const wsUrl = 'ws://localhost:9222/devtools/page/...';
    const ws = new WebSocket(wsUrl, { perMessageDeflate: false });
    
    ws.on('open', () => {
      ws.send(JSON.stringify({ id: 1, method: 'Page.captureScreenshot', params: { format: 'png', captureBeyondViewport: false } }));
    });
    
    ws.on('message', (data) => {
      const msg = JSON.parse(data);
      if (msg.id === 1) {
        const base64 = msg.result.data;
        fs.writeFileSync('screenshot.png', Buffer.from(base64, 'base64'));
        console.log('Screenshot saved as screenshot.png');
        ws.close();
      }
    });
  6. Run the script. Execute node shot.js in the terminal. The screenshot will be saved in the same folder.
  7. For full-page screenshots, adjust the capture command. Change the captureBeyondViewport parameter to true and also set fromSurface: true (default). This captures the entire scrollable page. Example:
    params: { format: 'png', captureBeyondViewport: true }
  8. To capture a specific element, use DOM queries. First, get the element's bounding box via DOM.getBoxModel, then pass the coordinates to Page.captureScreenshot with clip parameter. This is more advanced but useful for UI tests.

Common Mistakes

  • Forgetting to close all Chrome instances before launching with the debugging flag – otherwise the flag is ignored.
  • Using the wrong WebSocket URL (e.g., from the browser's devtools instead of the JSON endpoint).
  • Not waiting for the page to load before capturing – the screenshot may be blank or partial.
  • Using captureBeyondViewport: false when you intended a full page, resulting in only the visible viewport.
  • Assuming the screenshot is saved as a file immediately – the base64 data must be decoded and written to disk.

Tips

  • Use Page.enable before capturing to ensure the page is ready, especially for dynamic content.
  • Set a device scale factor via Emulation.setDeviceMetricsOverride to capture at higher resolution (e.g., 2x for retina).
  • For repeated captures, reuse the same WebSocket connection instead of opening a new one each time.
  • Add a delay (e.g., setTimeout) after navigation to let images and fonts load.
  • Capture in JPEG format for smaller file sizes if PNG is not required.

Troubleshooting

  • "Could not connect to WebSocket" – Check that Chrome is still running with the debugging port. Try curl http://localhost:9222/json to see if the endpoint responds.
  • Blank or black screenshot – The page may not have loaded. Add a wait for the Page.loadEventFired event before capturing.
  • Error: "Cannot find context with specified id" – This happens when the page is navigated or reloaded. Re-fetch the WebSocket URL from the JSON endpoint.
  • Port 9222 already in use – Use a different port, e.g., --remote-debugging-port=9223, and update the URL accordingly.
  • Screenshot is cropped or not full page – Ensure captureBeyondViewport is set to true and the page has no fixed-height containers that prevent scrolling.
  • Node script exits immediately – The WebSocket may close before the response arrives. Add a setTimeout to keep the process alive, or use an async/await pattern with a promise.

Frequently Asked Questions

Does this work with any browser?

CDP is Chrome-specific. Firefox and Safari have their own protocols, but the same concept applies with different commands.

Can I take a screenshot without launching a new Chrome window?

Yes, use headless mode: add --headless to the launch command. The rest of the steps remain the same.

How do I capture a screenshot of a page that requires login?

Log in manually in the Chrome instance before running the script. The session cookies will be used for the capture.

Is there a way to capture screenshots from a remote server?

Yes, but you must expose the debugging port securely (e.g., via SSH tunnel) and use the server's IP instead of localhost.

What is the maximum image size?

There's no hard limit, but very large pages may produce huge base64 strings. Use JPEG format and adjust quality to reduce size.

Can I capture a screenshot of a specific iframe?

Yes, use Page.getFrameTree to find the iframe's frameId, then pass it as the frameId parameter in Page.captureScreenshot.