文件结构:
screenshot
|-- background.js ---> service_worker运行的js
|-- images ---> 图片
| |-- logo-128x128.png
| |-- logo-16x16.png
| |-- logo-32x32.png
| `-- logo-48x48.png
`-- manifest.json ---> JSON文件描述了扩展程序的功能和配置
1 directory, 6 files
manifest.json文件:
{
"manifest_version": 3, // manifest版本
"name": "screenshot", // 名称
"description": "截图", // 描述
"version": "1.0", // 版本
"icons": {
// 扩展程序页面的图片
"16": "images/logo-16x16.png",
"32": "images/logo-32x32.png",
"48": "images/logo-48x48.png",
"128": "images/logo-128x128.png"
},
"background": {
"service_worker": "background.js"
},
"action": {
// 扩展程序工具栏上的主图片
"default_icon": {
"16": "images/logo-16x16.png",
"32": "images/logo-32x32.png",
"48": "images/logo-48x48.png",
"128": "images/logo-128x128.png"
}
},
// 权限
"permissions": [
"activeTab",
"downloads"
],
// 命令
"commands": {
"shortcut": {
"suggested_key": {
"default": "Ctrl+Shift+S",
"mac": "Command+Shift+S"
},
"description": "截图"
}
}
}
background.js文件:
// 点击扩展的图标截图
// https://developer.chrome.com/docs/extensions/reference/api/action?hl=zh-cn
chrome.action.onClicked.addListener(async function () {
// https://developer.chrome.com/docs/extensions/reference/api/tabs?hl=zh-cn
const screenshotUrl = await chrome.tabs.captureVisibleTab(); // 截取指定窗口中当前处于活动状态的标签页的显示区域
console.log(screenshotUrl);
// https://developer.chrome.com/docs/extensions/reference/api/downloads?hl=zh-cn#method-download
// https://github.com/GoogleChrome/chrome-extensions-samples/blob/main/_archive/mv2/api/downloads/download_links/manifest.json
chrome.downloads.download(
{
// url、文件名、是否另存为
url: screenshotUrl,
filename: "screenshot-by-click",
saveAs: true
},
);
});
// 使用快捷键截图
// https://developer.chrome.com/docs/extensions/reference/api/commands?hl=zh-cn
chrome.commands.onCommand.addListener(async function (command) {
if (command == "shortcut") {
// https://developer.chrome.com/docs/extensions/reference/api/tabs?hl=zh-cn
const screenshotUrl = await chrome.tabs.captureVisibleTab(); // 截取指定窗口中当前处于活动状态的标签页的显示区域
console.log(screenshotUrl);
// https://developer.chrome.com/docs/extensions/reference/api/downloads?hl=zh-cn#method-download
// https://github.com/GoogleChrome/chrome-extensions-samples/blob/main/_archive/mv2/api/downloads/download_links/manifest.json
chrome.downloads.download(
{
// url、文件名、是否另存为
url: screenshotUrl,
filename: "screenshot-by-command",
saveAs: true
},
);
}
});
扩展程序页面:
完整代码:
https://gitcode.com/janthinasnail/screenshot
详见:
https://developer.chrome.com/docs/extensions/reference/api/action?hl=zh-cn
https://developer.chrome.com/docs/extensions/reference/api/commands?hl=zh-cn
https://developer.chrome.com/docs/extensions/reference/api/tabs?hl=zh-cn
https://developer.chrome.com/docs/extensions/reference/api/downloads