User Agents

Web browsers and everyday web tech, explained

Capture a Tab Screenshot in a Chrome Extension

· 5 min read · Extensions

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

This guide shows you how to build a Chrome extension that captures a screenshot of the currently active tab. You'll use the chrome.tabs.captureVisibleTab API, which returns a data URL of the visible area of the tab. You'll need basic knowledge of HTML, CSS, and JavaScript, plus a Chrome browser for testing.

What You'll Need

  • Chrome browser (any recent version)
  • A text editor (VS Code, Sublime, etc.)
  • Basic understanding of JavaScript and Chrome extension manifest files

Step-by-Step

  1. Create the extension folder. Make a new directory on your computer, e.g., tab-screenshot-extension. All your files will go here.
  2. Create the manifest file. Inside the folder, create a file named manifest.json. Copy the following code into it:
    {
      "manifest_version": 3,
      "name": "Tab Screenshot",
      "version": "1.0",
      "permissions": ["activeTab", "tabs"],
      "action": {
        "default_popup": "popup.html"
      },
      "icons": {
        "16": "icon16.png",
        "48": "icon48.png",
        "128": "icon128.png"
      }
    }

    Note: The activeTab permission is enough for capturing the current tab when the user clicks the extension. The tabs permission is optional but may be needed for some advanced use cases.

  3. Create the popup HTML. Create a file named popup.html with a button and an image placeholder:
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        body { width: 300px; padding: 10px; }
        button { width: 100%; padding: 8px; }
        img { max-width: 100%; margin-top: 10px; }
      </style>
    </head>
    <body>
      <button id="capture">Capture Tab</button>
      <img id="screenshot" alt="Screenshot will appear here">
      <script src="popup.js"></script>
    </body>
    </html>
  4. Create the popup JavaScript. Create a file named popup.js with the following code:
    document.getElementById('capture').addEventListener('click', async () => {
      try {
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (!tab) {
          throw new Error('No active tab found');
        }
        const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, { format: 'png' });
        const img = document.getElementById('screenshot');
        img.src = dataUrl;
      } catch (error) {
        console.error(error);
        alert('Failed to capture screenshot: ' + error.message);
      }
    });

    This code queries the active tab, then calls captureVisibleTab with the window ID. The returned data URL is set as the image source.

  5. Add icons (optional but recommended). Create simple PNG icons named icon16.png, icon48.png, and icon128.png in the same folder. You can use any image editor or generate them online.
  6. Load the extension in Chrome. Open Chrome and go to chrome://extensions. Enable "Developer mode" (toggle in the top right). Click "Load unpacked" and select your extension folder.
  7. Test the extension. Click the extension icon in the toolbar to open the popup, then click "Capture Tab". You should see the screenshot of the current tab appear in the popup.
  8. Save the screenshot (optional). To save the image, you can add a download link in the popup. Modify popup.js to create a download link after capturing:
    const link = document.createElement('a');
    link.href = dataUrl;
    link.download = 'tab-screenshot.png';
    link.textContent = 'Download';
    document.body.appendChild(link);

Common Mistakes

  • Missing permissions: Forgetting to add activeTab or tabs in the manifest will cause the API to fail with an error.
  • Using Manifest V2: The code above is for Manifest V3. If you use V2, the API calls are similar but the manifest structure differs (e.g., browser_action instead of action).
  • Not handling async errors: The captureVisibleTab call returns a Promise. If you don't use await or .catch(), errors will be silent.
  • Capturing from background script: If you try to call captureVisibleTab from a background service worker without a user gesture, it may fail. Always call it from a popup or content script after a user action.
  • Wrong window ID: Using tab.windowId is correct, but if you use chrome.windows.getCurrent() you might get the wrong window if the popup is focused. Stick with the tab's window ID.

Tips

  • Use JPEG for smaller size: Change { format: 'png' } to { format: 'jpeg', quality: 80 } to get a smaller image, though with some loss of quality.
  • Capture only a specific area: The captureVisibleTab API captures the whole visible area. To crop, you can draw the image onto a canvas and then crop it using canvas methods.
  • Handle multiple windows: If the user has multiple windows, use chrome.tabs.query({ active: true }) (without currentWindow) to get the active tab in the last focused window.
  • Add a keyboard shortcut: You can add a command in the manifest to trigger the capture via a keyboard shortcut, which is more convenient for frequent use.
  • Test on different sites: Some sites (like Chrome Web Store or Chrome's internal pages) block screenshots due to security restrictions. Test on normal websites.

Troubleshooting

  • Error: "Cannot access a chrome:// URL" – You cannot capture screenshots of Chrome's internal pages (like chrome://extensions). Navigate to a regular website and try again.
  • Error: "Extension manifest invalid" – Check the JSON syntax in manifest.json. Missing commas or quotes are common mistakes. Use a JSON validator.
  • Button click does nothing – Open the popup's developer console (right-click inside popup, select "Inspect") to see any JavaScript errors. Make sure popup.js is correctly linked and there are no typos.
  • Screenshot is blank or black – This can happen if the tab is not fully loaded or if the tab is in a background state. Wait for the page to load completely and try again.
  • Permission errors in console – Double-check that you have included "activeTab" in the permissions array. Also, ensure you are not using the tabs permission unnecessarily if it's not needed.
  • Works in popup but not in background script – The API requires a user gesture context. If you need to capture from a background script, you must first listen for a user action (like a keyboard shortcut) before calling the API.

Frequently Asked Questions

Can I capture the full page, not just the visible part?

No, captureVisibleTab only captures the visible viewport. To capture the full page, you need to use a different approach, such as injecting a script that scrolls and stitches screenshots together, or using the chrome.debugger API (which is more complex).

Do I need the tabs permission?

No, for basic capture you only need activeTab. The tabs permission is only required if you want to access tab URLs or titles without user interaction.

Can I capture a screenshot of a background tab?

No, captureVisibleTab only works for the visible tab in a given window. You cannot capture hidden or minimized tabs.

Is there a way to capture without opening the popup?

Yes, you can use a keyboard shortcut or a context menu item to trigger the capture. The user gesture is still required, but it doesn't have to be a popup click.

How do I save the screenshot automatically?

You can use the chrome.downloads API to save the data URL as a file. Add the "downloads" permission to your manifest and call chrome.downloads.download({ url: dataUrl, filename: 'screenshot.png' }).

Does this work on all websites?

Most websites, but not on Chrome's internal pages (e.g., chrome://), the Chrome Web Store, or sites that have strict security policies that block screenshots. You'll get an error in those cases.