Capture a Specific Area with JavaScript in a Chrome Extension
In this article
This guide shows you how to capture a specific area of a webpage (like a selected region or a particular element) using JavaScript in a Chrome extension. You'll learn to use the Chrome tabs.captureVisibleTab API to take a screenshot, then crop it to the desired area using a canvas. This is useful for features like screenshot tools, annotation tools, or saving a portion of a page. You'll need basic knowledge of HTML, CSS, and JavaScript, plus a Chrome extension project set up (manifest file, background script, and popup or content script).
What You'll Need
- A Chrome extension project with a
manifest.json(Manifest V3 recommended). - Permissions in the manifest:
"activeTab"and"tabs"(or"if you need broader access)." - A way to trigger the capture (e.g., a popup button or a keyboard shortcut).
- Basic familiarity with Promises and the
canvaselement.
Step-by-Step
- Set up your manifest.json – Ensure you have the required permissions. For capturing the visible tab, you need
"activeTab"(which grants temporary access when the user invokes the extension) and"tabs"to read the tab's URL and title. Also declare a background service worker and a popup if you're using one. Example:"permissions": ["activeTab", "tabs"] - Create a trigger in your popup or content script – Add a button in your popup HTML that calls a function to start the capture. For example,
<button id="captureBtn">Capture Area</button>. - Get the active tab – In your popup script (or background script), use
chrome.tabs.query({active: true, currentWindow: true})to get the current tab object. - Capture the visible tab – Call
chrome.tabs.captureVisibleTab()with the window ID and options. This returns a data URL (base64-encoded PNG). Example:const dataUrl = await chrome.tabs.captureVisibleTab(windowId, {format: 'png'}); - Define the area to capture – Decide on the specific area. You can either let the user select a region (via a content script overlay) or programmatically target an element. For simplicity, we'll capture a fixed rectangle (e.g., x=100, y=100, width=400, height=300) or the bounding box of a known element (e.g.,
document.querySelector('#main')). - Load the screenshot into an image – Create an
Imageobject and set itssrcto the data URL. Wait for it to load usingawait new Promise(resolve => img.onload = resolve). - Draw the cropped area on a canvas – Create a
canvaselement, set its width and height to the desired crop size, then usectx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh). The parameterssx,syare the top-left corner of the area in the original screenshot, andsw,share the width and height. - Convert the canvas to a data URL – Use
canvas.toDataURL('image/png')to get the cropped image as a base64 string. - Use the cropped image – You can display it in the popup, download it, or send it to a server. For download, create an anchor element with
hrefset to the data URL anddownloadattribute set to a filename, then click it. - Handle user-selected areas (optional) – If you want the user to select an area, inject a content script that overlays a draggable selection rectangle. Capture the coordinates (relative to the viewport) and send them to the background script via
chrome.runtime.sendMessage. Then use those coordinates in the crop step.
Common Mistakes
- Not waiting for the image to load – Trying to draw the image on the canvas before it's fully loaded results in a blank canvas. Always use the
onloadevent or a Promise. - Using wrong coordinates – The captureVisibleTab screenshot is of the visible viewport, not the whole page. If you use coordinates from a content script that account for scrolling, you'll need to adjust by the scroll offset.
- Missing permissions – Without
"activeTab", the capture will fail with an error. Also,captureVisibleTabonly works on the active tab in the current window. - Canvas tainting – If the page contains cross-origin images (e.g., from a CDN), the canvas may become tainted, and
toDataURL()will throw a SecurityError. To avoid this, you can request the screenshot withformat: 'png'(which is fine), but note that the screenshot itself is not tainted because it's a browser-generated image. - Ignoring device pixel ratio – On high-DPI screens, the screenshot dimensions may be larger than CSS pixels. Use
window.devicePixelRatioto scale coordinates if needed.
Tips
- Use the activeTab permission – It gives you access to the tab only when the user invokes the extension, which is more secure and doesn't require broad host permissions.
- Make the selection UI responsive – If you build a selection overlay, ensure it accounts for page scrolling and zoom level.
- Test on different zoom levels – The screenshot dimensions change with browser zoom. Use
chrome.tabs.getZoom()to adjust coordinates if necessary. - Consider using OffscreenCanvas – In newer Chrome versions, you can use
OffscreenCanvasfor better performance, but it's not necessary for simple crops. - Download with a proper filename – Use a timestamp or a descriptive name to avoid overwriting.
Troubleshooting
- Capture returns undefined or an error – Check that the tab is active and the window is not minimized. Also ensure you have the correct permissions. If you're using a keyboard shortcut, make sure it's declared in the manifest.
- Canvas is blank – Double-check that you waited for the image to load. Also verify that the crop coordinates are within the bounds of the screenshot.
- SecurityError when calling toDataURL – This usually means the canvas is tainted. Since you're drawing a screenshot (which is a browser-generated image), this should not happen. If it does, ensure you're not drawing any other images onto the canvas.
- Coordinates are off – If you're using coordinates from a content script, remember that they are relative to the document, not the viewport. Subtract
window.scrollXandwindow.scrollYto get viewport-relative coordinates. - Capture works but only captures part of the page –
captureVisibleTabonly captures the visible portion. To capture the whole page, you'd need a different approach, like usingchrome.debuggeror a third-party library.
Frequently Asked Questions
Can I capture a specific element without user selection?
Yes, you can programmatically get the element's bounding box using getBoundingClientRect() in a content script, then send those coordinates to the background script for cropping.
Does the capture work on pages with iframes?
No, captureVisibleTab captures the top-level page. If you need to capture an iframe, you'd have to use a different method, such as taking a screenshot of the iframe's content via a separate tab or using the chrome.debugger API.
Can I capture a region that is scrolled out of view?
No, captureVisibleTab only captures the currently visible viewport. To capture off-screen content, you'd need to scroll the page first or use a full-page screenshot method.
Is there a way to let the user drag a selection rectangle?
Yes, you can inject a content script that creates a draggable overlay. Capture the start and end coordinates, then send them to the background script to crop.
How do I save the cropped image to disk?
Create an anchor element with the href set to the data URL and the download attribute set to a filename, then programmatically click it. This works in the extension's popup or background page.
Why does my capture fail on Chrome Web Store pages?
Chrome restricts extensions from capturing certain sensitive pages like the Chrome Web Store or the Chrome New Tab page. You'll need to handle these cases gracefully, perhaps by showing an error message.