上篇Chrome拓展(插件)入门篇介绍了拓展基本概念、配置清单manifest.json以及清单中的action字段
本篇介绍 background、permissions、icons、options_page 字段以及相关联的
Chrome API的使用
创建你的第二个拓展插件
效果演示:

配置清单manifest.json
{
"manifest_version": 3,
"name": "预算管理",
"description": "跟踪你的消费支出",
"version": "1.0",
"action": {
"default_icon": {
"16": "images/jjy16.png",
"32": "images/jjy32.png",
"48": "images/jjy48.png",
"64": "images/jjy64.png"
},
"default_popup": "popup.html"
},
"background": {
"service_worker": "eventPage.js",
"type": "module"
},
"permissions": [
"storage",
"notifications",
"contextMenus"
],
"icons": {
"16": "images/jjy16.png",
"32": "images/jjy32.png",
"48": "images/jjy48.png",
"64": "images/jjy64.png"
},
"options_page": "options.html"
}
上篇已经介绍过的就不在细说。
background:“ background”字段下的清单中注册 background scripts。这个字段使用“ service _ worker”键,并指定一个 JavaScript 文件
使用 Service Worker 管理事件
扩展程序是基于事件的程序,事件是浏览器触发器,例如导航到新页面、删除书签,或关闭选项卡。扩展使用 background service worker中的脚本监控这些事件,然后响应指定的指令。
还可以选择指定一个额外的字段“ type”: “ Module”,这样就能在 Service Worker 使用 ES Module 编程。
permissions:声明权限
要使用大多数 chrome.* API,必须在manifest的permissions字段中声明其意图。
扩展可以请求三类权限,使用清单中的相应键指定:
permissions包含已知字符串列表中的项目(例如“地理位置”)optional_permissions就像普通的permissions,但由扩展的用户在运行时授予,而不是提前host_permissions包含一个或多个匹配模式,可以访问一个或多个主机
可用的权限列表:权限列表
| 字段 | 描述 |
|---|---|
| storage | 存储权限 ,使用chrome.storageAPI来存储、检索和跟踪用户数据的更改。 |
| notifications | 使用chrome.notificationsAPI权限,创建丰富的通知,并在系统托盘中显示这些通知。 |
| contextMenus | 右键上下文菜单权限,使扩展程序可以访问chrome.contextMenus API。 |
icons:扩展程序、应用程序或主题的图标。Chrome会自动匹配合适大小的图标。
options_page:指定设置选项页面。右键【选项】跳转的页面。
文件结构

popup.js
$(function () {
// 使用chrome.storageAPI 来存储、检索和跟踪用户数据的更改。
chrome.storage.sync.get(['total', 'limit'], function (budget) {
$('#total').text(budget.total);
$('#limit').text(budget.limit);
});
// 当用户点击支出按钮时触发事件
$('#spendAmount').click(() => {
// 首先获取已经存储的数据
chrome.storage.sync.get(['total', 'limit'], (budget) => {
// 重新计算总支出
let newTotal = 0;
if (budget.total) {
newTotal += parseInt(budget.total);
}
// 获取输入的金额计算总支出
let amount = $('#amount').val();
if (amount) {
newTotal += parseInt(amount);
}
// 将最新的计算的总支出存储起来
chrome.storage.sync.set({ 'total': newTotal }, () => {
if (amount && newTotal >= budget.limit) {
// 创建并显示通知
let Options = {
type: "basic",
iconUrl: "images/jjy64.png",
title: "过度消费警告!",
message: "你的消费支出已经达到限额,请理性消费!"
};
// limitNotification 通知标识符。如果没有设置或为空,将自动生成一个 ID。
chrome.notifications.create(Options);
}
});
// 按钮动画
$("#spendAmount").addClass("onclic", 50, validate());
// 更新界面
$('#total').text(newTotal);
$('#amount').val('');
});
});
// 按钮动画样式
function validate() {
setTimeout(() => {
$("#spendAmount").removeClass("onclic");
$("#spendAmount").addClass("validate", 50, callback());
}, 500);
}
function callback() {
setTimeout(() => {
$("#spendAmount").removeClass("validate");
}, 500);
}
});
完整源码:https://download.csdn.net/download/qq_44721831/59689782
如果无法下载,可以评论告知,另行上传
2150

被折叠的 条评论
为什么被折叠?



