最近有个项目需要用的谷歌插件,于是乎来学习一下,看到很多都是V2版本的,但是2023年一月份谷歌就要用V3替代掉了,发文记录一下自己跟着谷歌文档学习的过程,对于有前端基础的朋友,我想你能很快上手的,话不多说,下面是wolai文档的链接,进入一起学习吧!
谷歌插件学习(入门)
manifest,json
{
"name": "我的谷歌插件",
"description": "谷歌插件学习",
"version": "1.0",
"manifest_version": 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"
}
background.js
let color = '#3aa757';
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({ color });
console.log('Default background color set to %cgreen', `color: ${color}`);
});
popup.html
popup.js
// 使用用户首选颜色初始化按钮
let changeColor = document.getElementById("changeColor");
// changeColor.onclick = () => {
// chrome.storage.sync.get("color", ({ color }) => {
// changeColor.style.backgroundColor = color;
// });
// };
// 单击按钮时,将setPageBackgroundColor注入当前页面
changeColor.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: setPageBackgroundColor,
});
});
// 此函数的主体将作为当前页面内的内容脚本执行
function setPageBackgroundColor() {
chrome.storage.sync.get("color", ({ color }) => {
document.body.style.backgroundColor = color;
});
}
button.css
button {
height: 30px;
width: 150px;
outline: none;
margin: 10px;
border: none;
border-radius: 2px;
}
button.current {
box-shadow: 0 0 0 2px white,
0 0 0 4px black;
}
options.html
选择不同的背景颜色!
options.js
// options.js
let page = document.getElementById("buttonDiv");
let selectedClassName = "current";
const presetButtonColors = [
"#3aa757",
"#e8453c",
"#f9bb2d",
"#4688f1"
];
// 通过标记所选按钮并保存选择,对按钮单击做出反应
function handleButtonClick(event) {
// 从以前选择的颜色中删除样式
let current = event.target.parentElement.querySelector(
`.${selectedClassName}`
);
if (current && current !== event.target) {
current.classList.remove(selectedClassName);
}
// 将按钮标记为选中
let color = event.target.dataset.color;
event.target.classList.add(selectedClassName);
chrome.storage.sync.set({ color });
}
// 为提供的每种颜色在页面上添加一个按钮
function constructOptions(buttonColors) {
chrome.storage.sync.get("color", (data) => {
let currentColor = data.color;
// 对应我们提供的每种颜色…
for (let buttonColor of buttonColors) {
// …创建具有该颜色的按钮…
let button = document.createElement("button");
button.dataset.color = buttonColor;
button.style.backgroundColor = buttonColor;
// …标记当前选定的颜色…
if (buttonColor === currentColor) {
button.classList.add(selectedClassName);
}
// …并为单击该按钮时注册侦听器
button.addEventListener("click", handleButtonClick);
page.appendChild(button);
}
});
}
// 通过构造颜色选项初始化页面
constructOptions(presetButtonColors);