Screenshot a Single Element with CDP
In this article
This guide shows you how to capture a screenshot of just one element on a page—like a button, a chart, or a specific div—using the Chrome DevTools Protocol (CDP). This is useful for generating clean UI assets, testing visual regressions, or saving a component without the surrounding page clutter. You'll need a basic understanding of JavaScript and either a Node.js environment or a browser's developer console to run the commands.
What You'll Need
- Chrome or Chromium browser (version 60+ for full CDP support)
- A way to send CDP commands: either via Node.js with the
chrome-remote-interfacepackage, or directly in the browser's DevTools console using thefetchAPI to communicate with the DevTools endpoint. - Basic familiarity with the command line and JSON.
Step-by-Step
- Launch Chrome with the remote debugging port. Open a terminal and run:
On Windows, you may need to provide the full path to the Chrome executable. This starts Chrome with the DevTools Protocol listening on port 9222.chrome --remote-debugging-port=9222 - Navigate to the target page. In the same Chrome instance, go to the page containing the element you want to capture. Ensure the element is visible and fully loaded.
- Get the list of available tabs. In your terminal, run:
This returns a JSON list of open tabs. Find the entry for your page and copy itscurl http://localhost:9222/jsonwebSocketDebuggerUrlvalue. - Connect to the page via WebSocket. Use a WebSocket client (like
wscator a Node.js script) to connect to that URL. For example, with Node.js:
You'll replace the placeholder with the actual URL from step 3.const WebSocket = require('ws'); const ws = new WebSocket('ws://localhost:9222/devtools/page/...'); - Enable the necessary CDP domains. Send the following commands over the WebSocket:
This ensures the page and runtime events are available.{ "id": 1, "method": "Page.enable" } { "id": 2, "method": "Runtime.enable" } - Find the element's bounding box. Use JavaScript to get the element's position and size. Send:
Replace{ "id": 3, "method": "Runtime.evaluate", "params": { "expression": "JSON.stringify(document.querySelector('#my-element').getBoundingClientRect())", "returnByValue": true } }#my-elementwith your actual selector. The response will containleft,top,width, andheight. - Capture the screenshot. Send the
Page.captureScreenshotcommand with a clip parameter that matches the element's bounding box:
Replace{ "id": 4, "method": "Page.captureScreenshot", "params": { "format": "png", "captureBeyondViewport": true, "clip": { "x": left, "y": top, "width": width, "height": height, "scale": 1 } } }left,top, etc. with the values from step 6. The response will include a base64-encoded PNG image. - Decode and save the image. In your Node.js script, decode the base64 string and write it to a file:
You now have a screenshot of just that element.const fs = require('fs'); fs.writeFileSync('element.png', Buffer.from(data.result.data, 'base64'));
Common Mistakes
- Using the wrong selector. Make sure the selector matches exactly one element. If it matches multiple,
getBoundingClientRect()will only return the first one. - Forgetting to enable domains. Skipping
Page.enableorRuntime.enablecan cause commands to fail silently. - Not accounting for page scroll. The bounding box coordinates are relative to the viewport. If the page is scrolled, the screenshot may capture the wrong area. Use
captureBeyondViewport: trueand adjust the clip coordinates to be absolute (add scroll offsets). - Element not fully loaded. If the element is lazy-loaded or animated, wait for it to be stable before capturing.
Tips
- Use
scalein the clip to capture at higher resolution (e.g., 2 for retina displays). - For a quick test, you can run the CDP commands directly in the browser's DevTools console using
fetchto the local endpoint, but it's easier to use a Node.js script for automation. - If the element has a shadow DOM, you'll need to pierce it using
document.querySelector('my-element').shadowRoot.querySelector(...). - Consider using
Page.getLayoutMetricsto get the full page size if the element is outside the initial viewport.
Troubleshooting
- Screenshot is blank or black: Make sure the element is visible and not covered by another element. Also, check that the clip coordinates are correct—try logging them to the console.
- WebSocket connection fails: Ensure Chrome is running with the remote debugging port and that no firewall is blocking the connection. Try
curl http://localhost:9222/json/versionto verify. - Element not found: The selector might be wrong or the element is inside an iframe. Use
document.querySelectorAllto verify the element exists, and if in an iframe, switch to that frame usingPage.getFrameTreeandPage.navigateor evaluate within the frame context. - Coordinates are off: This often happens when the page is scrolled. Add
window.scrollXandwindow.scrollYto thexandyvalues in the clip. - Image is blurry: Increase the
scalevalue in the clip (e.g., 2) to capture at higher resolution.
Frequently Asked Questions
Can I use CDP without a WebSocket library?
Yes, you can use the HTTP endpoint /json/new?url to open a new tab, but for actual commands you need WebSocket. In Node.js, you can use the built-in WebSocket (available in Node 21+) or install the ws package.
Does this work with headless Chrome?
Yes, headless Chrome supports CDP. Start it with --headless --remote-debugging-port=9222 and follow the same steps.
Can I screenshot an element that is not in the current viewport?
Yes, set captureBeyondViewport to true and use absolute coordinates (add scroll offsets) in the clip. Alternatively, scroll the element into view first using element.scrollIntoView().
How do I get the element's bounding box if it's inside an iframe?
You need to evaluate the script inside the iframe's context. Use Runtime.evaluate with contextId obtained from Page.getFrameTree or Runtime.executionContextCreated events.
Can I capture a JPEG instead of PNG?
Yes, set format to jpeg in the Page.captureScreenshot parameters. JPEG files are smaller but may lose quality.
Is there a way to do this without writing code?
There are third-party tools like Puppeteer that wrap CDP and provide a simpler API, but they still require some coding. For a no-code solution, you could use browser extensions that capture elements, but they may not offer the same precision.