1、下载demo: 一个来源于官方的基础例子
2、解释一下配置信息:
{
"name": "Getting Started Example", //名字
"description": "Build an Extension!", //描述
"version": "1.0", //版本
"manifest_version": 3, //mainfest版本 2或3
"background": {
"service_worker": "background.js"
},
//插件权限
"permissions": ["storage", "activeTab", "scripting"],
"action": { //插件页面显示
"default_popup": "popup.html",
"default_icon": {
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
}
},
"icons": { //图标
"16": "/images/get_started16.png",
"32": "/images/get_started32.png",
"48": "/images/get_started48.png",
"128": "/images/get_started128.png"
},
"options_page": "options.html" //选项功能页,非必须
}
其中name,version.mainfest\_version三个属性必不可少;
backgroud 是一个常驻的页面,它的生命周期是插件中所有类型页面中最长的,它随着浏览器的打开而打开,随着浏览器的关闭而关闭,所以通常把需要一直运行的、启动就运行的、全局的代码放在background里面。
3、主要代码:
popup.html
<!DOCTYPE html>
<html>
<head>
<title>删除稿件插件</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div class="pop-wrap">
<button id="startDel">删除</button>
</div>
<script src="libs/jquery-3.6.0.min.js"></script>
<script src="popup.js"></script>
</body>
</html>
popup.js
// Initialize butotn with users's prefered color
let startDel = document.getElementById("startDel");
// When the button is clicked, inject setPageBackgroundColor into current page
startDel.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
//function: setPageBackgroundColor,
files :['delbdwk.js'],
});
});
// The body of this function will be execuetd as a content script inside the
// current page
function setPageBackgroundColor() {
console.log('执行一些操作...')
}
files属性是执行的业务代码;