项目结构
最基础的文件是manifest.json和一个作为插件页面的html,还有一个16*16的插件图标
manifest
manifest.json一般会包含以下内容
{
"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就是用来设置插件被点击的页面的,我这里用的是index.html。这个html页面可以和普通html一样引入css和js,本质就是一个普通web页面
permissions这个需要根据你用到的权限设置
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.
对标签页进行操作需要chrome.scripting namespace,js操作和读取页面内容都需要这个。因该是设置了以后在插件的运行环境和serviceworker里面都可以调用。
background这个用来设置一个后台的worker,用于注册对浏览器时间的监听(monitor browser events),比如修改右键菜单就需要这个。
页面例子
官方文档的例子不过我们用不到。
//index.html
<html>
<body>
<h1>Hello Extensions</h1>
<script src="popup.js"></script>
</body>
</html>
//popup.js
console.log('This is a popup!');
下载的全部代码
/**
* 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
});
}
});
service worker的使用
创建右键菜单项和绑定click事件需要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
});
}
});
页面代码的注入
//官网例子,也是有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],
});
}
})
灵感来源是看了下面的文章
原文用的这个one liner虽然看起很酷但是可读性太差了,我不是很喜欢这种语法糖,而且js语法糖都很丑
[].map.call(document.getElementByTagName('img'), img => img.src)
原文引用一下,我看到这才知道有这么个接口,这download因为是浏览器的不受fetch和跨域等的影响:
上上述代码中,用了一个chrome的download接口,其中的conflictAction属性有三个选项: 这儿用的是overwrite(覆盖),还有uniquify(后面加(num)),最后一个是prompt(提示用户自己决定重命名还是啥)。
而且原文代码用的还是chrome.tabs.executeScript,这个已经在官方文档废弃了,现在是chrome.scripting.executeScript。
而且原文用的还是callback形式的api,现在promise api代码可读性更好。
-
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
-
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
-
chrome-extensions-samples. branch main. commit 688fa93. https://github.com/GoogleChrome/chrome-extensions-samples/blob/main/api-samples/contextMenus/basic/sample.js
还有一个官方下载的小例子
- chrome-extensions-samples. branch main. commit b5e3683. https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/_archive/mv2/extensions/download_images