Learning Chrome extension development by building an image downloader

March 4, 2024

Project structure

At minimum I need a manifest.json, an HTML file for the extension’s page, and a 16 × 16 icon.

The manifest

A manifest.json typically contains the following:

{
    "name": "Download Extensions",
    "description": "Base Level Extension",
    "version": "0.0.1",
    "manifest_version": 3,
    "action": {
      "default_popup": "index.html",
      "default_icon": "hello_extensions.png"
    },
    "permissions": ["activeTab", "scripting", "contextMenus", "downloads", "tabs"],
    "background": {
        "service_worker": "service_worker.js",
        "type": "module"

    },
    "icons": {
        "16": "hello_extensions.png"
    }
}

default_popup selects the page shown when someone clicks the extension. I use index.html here. It can load CSS and JavaScript like any other HTML document. In essence it is an ordinary web page.

Set permissions according to the APIs the extension actually uses.

An Extensions API consists of a namespace containing methods and properties for doing extensions work, and usually, but not always, manifest fields for the manifest.json file. For example, the chrome.action namespace requires an "action" object in the manifest. Many APIs also require permissions in the manifest.

For scripting a tab or reading its page contents, I use the chrome.scripting namespace. Once configured, I expect it to be available from the extension environment and the service worker.

The background entry configures a worker that listens for browser events. For instance, I use it to modify the context menu.

Example page

Here is an example from the official docs, though we do not need it for this extension.

//index.html
<html>
  <body>
    <h1>Hello Extensions</h1>
    <script src="popup.js"></script>
  </body>
</html>

//popup.js
console.log('This is a popup!');

Complete download code

/**
 * service_worker.js
 * "background": {"service_worker": "service_worker.js","type": "module"},
 * type module enable it to import from other js file
*/
import './context_menu.js';

/**
 * context_menu.js
*/
chrome.contextMenus.onClicked.addListener(genericOnClick);
const SAVE_ALL_IMAGES = 'save_all_images';

async function getCurrentTab() {
    let queryOptions = { active: true, lastFocusedWindow: true };
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    let [tab] = await chrome.tabs.query(queryOptions);
    return { tabId: tab.id };
}

function save_all_images() {
    console.log('save_all_images');
    //get all src of images on the html page
    let imgs = document.querySelectorAll('img');
    let imageSrcs = [];
    imgs.forEach(img => {
        imageSrcs.push(img.src);
    });
    // download all images, the script excutes in current webpage not the service worker chrome.downloads.download is only available in the service worker script
    // for (let i = 0; i < imageSrcs.length; i++) {
    //   chrome.downloads.download({
    //     conflictAction: 'uniquify',
    //     url: imageSrcs[i],
    //     filename: 'image' + i + '.png'
    //   });
    // }
    console.log(imageSrcs);
    return imageSrcs;
}

// A generic onclick callback function.
async function genericOnClick(info) {
    switch (info.menuItemId) {
        case SAVE_ALL_IMAGES:
            // Radio item function
            console.log(`${info.menuItemId} clicked.`);

            chrome.scripting
                .executeScript({
                    target: await getCurrentTab(),
                    func: save_all_images,
                })
                .then((res) => {
                    console.log(res)
                    let imageSrcs = res[0].result;
                    for (let i = 0; i < imageSrcs.length; i++) {
                        chrome.downloads.download({
                            conflictAction: 'uniquify',
                            url: imageSrcs[i],
                            // filename: 'image' + i + '.png'
                        });
                    }
                })

            break;
        default:
            // Standard context menu item function
            console.log('Standard context menu item clicked.');
    }
}

    /**
     * contexts
     * [ContextType,...ContextType[]] optional
     * List of contexts this menu item will appear in. Defaults to ['page'].
    */
// chrome.runtime.onInstalled.addListener(function () {
//     // Create one test item for each context type.
//     // context决定了在哪种情况下点击右键菜单能显示出来 例如page表示在页面上右键点击才能显示出来
//     let contexts = [
//       'page',
//       'selection',
//       'link',
//       'editable',
//       'image',
//       'video',
//       'audio'
//     ];
//     for (let i = 0; i < contexts.length; i++) {
//       let context = contexts[i];
//       let title = "Test '" + context + "' menu item";
//       chrome.contextMenus.create({
//         title: title,
//         contexts: [context],
//         id: context
//       });
//     }
  
//     // Create a parent item and two children.
//     let parent = chrome.contextMenus.create({
//       title: 'Test parent item',
//       id: 'parent'
//     });
//     chrome.contextMenus.create({
//       title: 'Child 1',
//       parentId: parent,
//       id: 'child1'
//     });
//     chrome.contextMenus.create({
//       title: 'Child 2',
//       parentId: parent,
//       id: 'child2'
//     });
  
//     // Create a radio item.
//     chrome.contextMenus.create({
//       title: 'radio',
//       type: 'radio',
//       id: 'radio'
//     });
  
//     // Create a checkbox item.
//     chrome.contextMenus.create({
//       title: 'checkbox',
//       type: 'checkbox',
//       id: 'checkbox'
//     });
  
//     // Intentionally create an invalid item, to show off error checking in the
//     // create callback.
//     chrome.contextMenus.create(
//       { title: 'Oops', parentId: 999, id: 'errorItem' },
//       function () {
//         if (chrome.runtime.lastError) {
//           console.log('Got expected error: ' + chrome.runtime.lastError.message);
//         }
//       }
//     );
//   });


chrome.runtime.onInstalled.addListener(function () {
    // Create one test item for each context type.
    let contexts = [
        SAVE_ALL_IMAGES,
    ];
    for (let i = 0; i < contexts.length; i++) {
        let context = contexts[i];
        let title = contexts[i];
        chrome.contextMenus.create({
            title: title,
            id: context
        });
    }
});

Using the service worker

To create a context-menu entry and register its click handler, run the following in the worker:

chrome.contextMenus.onClicked.addListener(genericOnClick);
chrome.runtime.onInstalled.addListener(function () {
    // Create one test item for each context type.
    let contexts = [
        SAVE_ALL_IMAGES,
    ];
    for (let i = 0; i < contexts.length; i++) {
        let context = contexts[i];
        let title = contexts[i];
        chrome.contextMenus.create({
            title: title,
            id: context
        });
    }
});

Injecting code into the page

//官网例子,也是有callback形式,但是这个更简洁
async function getCurrentTab() {
    let queryOptions = { active: true, lastFocusedWindow: true };
    // `tab` will either be a `tabs.Tab` instance or `undefined`.
    let [tab] = await chrome.tabs.query(queryOptions);
    return { tabId: tab.id };
}


function save_all_images() {
    console.log('save_all_images');
    //get all src of images on the html page
    let imgs = document.querySelectorAll('img');
    let imageSrcs = [];
    imgs.forEach(img => {
        imageSrcs.push(img.src);
    });
    console.log(imageSrcs);
    return imageSrcs;
}

chrome.scripting
    .executeScript({
        target: await getCurrentTab(),// 必须传入{ tabId: tab.id }指明要注入到哪个标签页
        func: save_all_images, //注入并运行的代码
    })
    .then((res) => {
        console.log(res) //res是上述代码运行的返回值,这里是promise形式,曾经是callback,为了兼容callback的api还存在
        let imageSrcs = res[0].result; //因为代码会递归的在iframe里也执行所以可能有多个返回值,用frameid来区分,每个元素都有frameid和result
        for (let i = 0; i < imageSrcs.length; i++) {
            chrome.downloads.download({
                conflictAction: 'uniquify',
                url: imageSrcs[i],
            });
        }
    })

The article that gave me the idea

The original uses the one-liner below. It looks clever, but I find it hard to read. I don’t much like that kind of syntactic sugar in JavaScript.

[].map.call(document.getElementByTagName('img'), img => img.src)

This excerpt from the article introduced me to the download API. Because the browser handles the download, it behaves differently from fetch with respect to cross-origin requests:

The code above uses Chrome’s downloads API. Its conflictAction property has three choices. Here we use overwrite. The others are uniquify, which adds a number to the filename, and prompt, which lets the user decide what to do about the name.

The article also uses chrome.tabs.executeScript, which the official docs have deprecated. The current API is chrome.scripting.executeScript. The original uses callbacks. I find the promise-based API easier to read.

  1. Code_星华. (14 July, 2017.). chrome扩展-save all image(来自chrome官方文档. CSDN. [Blog post]. Retrieved Mar 4, 2024, from https://blog.csdn.net/hxh5801050/article/details/75106556

  2. extensions. (n.d.). Chrome docs. Retrieved Mar 04, 2024, from https://developer.chrome.com/docs/extensions/reference/api/contextMenus#examples https://developer.chrome.com/docs/extensions/reference/api/tabs#get_the_current_tab https://developer.chrome.com/docs/extensions/reference/api/scripting#handle_the_results https://developer.chrome.com/docs/extensions/reference/api/scripting#method-executeScript https://developer.chrome.com/docs/extensions/reference/api/downloads#type-DownloadOptions

  3. chrome-extensions-samples. branch main. commit 688fa93. https://github.com/GoogleChrome/chrome-extensions-samples/blob/main/api-samples/contextMenus/basic/sample.js

Another small download example from the official repository

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2024-03-04). Learning Chrome extension development by building an image downloader. https://caiborui.com/blog/2024-03-04-zh-chrome%E4%B8%8B%E8%BD%BD%E5%9B%BE%E7%89%87%E6%8F%92%E4%BB%B6-%E6%8F%92%E4%BB%B6%E5%BC%80%E5%8F%91%E5%AD%A6%E4%B9%A0-entrans

@misc{borui2024-bc01258e,
  author = {borui},
  title = {{Learning Chrome extension development by building an image downloader}},
  year = {2024},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2024-03-04-zh-chrome%E4%B8%8B%E8%BD%BD%E5%9B%BE%E7%89%87%E6%8F%92%E4%BB%B6-%E6%8F%92%E4%BB%B6%E5%BC%80%E5%8F%91%E5%AD%A6%E4%B9%A0-entrans}
}