A Simple Chrome Extension to Save Web Page Screenshots to Local Disk

A Chrome extension is a package of files including a manifest file, HTML files, JavaScript files and other resources. With extensions, we can add more functionalities to empower Chrome.

Getting Started with Chrome Extension

Anatomy of Web Page Screenshots

The manifest file:

{
  "name": "Screenshot Extension",
  "version": "1.0",
  "description": "A simple screenshot extension",
  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "browser_action": {
    "default_icon": "camera.png",
    "default_title": "Screenshot"
  },
  "permissions": ["tabs", "<all_urls>", "activeTab"],
  "manifest_version": 2
}
  • The background.js controls the logic of the extension, whereas content.js interacts with web pages. They send messages to communicate with each other.
  • If you want to make your extension work for all web sites, you have to set the permission ****

Capture the visible area of the web page when clicking the extension icon:

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.captureVisibleTab(
    null,
    {
      format: "png",
      quality: 100,
    },
    function (data) {
      screenshot.data = data;
    }
  );
});

Message passing between the extension and web pages:

  • In background.js
chrome.tabs.query(
  {
    active: true,
    currentWindow: true,
  },
  function (tabs) {
    chrome.tabs.sendMessage(
      tabs[0].id,
      { ready: "ready" },
      function (response) {
        if (response.download === "download") {
        }
      }
    );
  }
);
  • In content.js
chrome.extension.onMessage.addListener(function (msg, sender, sendResponse) {
  if (msg.ready === "ready") {
    if (confirm("Do you want to capture the screen?")) {
      sendResponse({ download: "download" });
    }
  }
});

Save the screenshot:

saveScreenshot : function() {
    var image = new Image();
        image.onload = function() {
            var canvas = screenshot.content;
            canvas.width = image.width;
            canvas.height = image.height;
            var context = canvas.getContext("2d");
            context.drawImage(image, 0, 0);
            // save the image
            var link = document.createElement('a');
            link.download = "download.png";
            link.href = screenshot.content.toDataURL();
            link.click();
            screenshot.data = '';
        };
        image.src = screenshot.data;
    },

Install and Run Chrome Extension

  • Check Developer mode.
  • Click Load unpacked extension to select your project folder.load chrome extension
  • Open a web page and click the extension icon in the toolbar.
  • Confirm and save the screenshot.

Download Sample Code

Chrome_Screenshot