目录
chrome插件开发 - 入门
官方文档:https://developer.chrome.com/docs/extensions/mv3/getstarted/(需要vpn)
插件中主要包含 background scripts(插件常驻进程), content scripts(注入网页的脚本), an options page(操作页面), UI elements(插件ui界面) 和许多逻辑代码。
扩展程序使用HTML, CSS, and JavaScript来开发。
1、清单文件
新件Helloworld文件夹,创建清单文件
manifest.json
{
"name": "HelloWorld",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3
}
进入扩展程序界面,打开开发者模式,加载我们编写的Helloworld文件夹。
加载完毕
2、background script
编写程序:扩展加载后给缓存中存储一个color变量。
需要在清单文件中注册,并指定脚本文件路径:
2.1 manifest.json添加background
{
"name": "HelloWorld",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
}
}
2.2 新建background.js
let color = '#3aa757';
// 插件首次安装调用
chrome.runtime.onInstalled.addListener(() => {
// set a value using the [storage] API
chrome.storage.sync.set({ color });
console.log('Default background color set to %cgreen', `color: ${color}`);
});
重载报错
2.3 清单文件中设置权限
{
"name": "HelloWorld",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage"]
}
点击service worker打开开发工具
3、用户界面
3.1 点击程序图标弹出界面
在清单文件中添加一个action对象,设置popup.html为默认弹出界面。
{
"name": "HelloWorld",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage"],
"action": {
"default_popup": "popup.html"
}
}
新建popup.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<button id="changeColor"></button>
</body>
</html>
button.css
button {
height: 30px;
width: 30px;
outline: none;
margin: 10px;
border: none;
border-radius: 2px;
}
button.current {
box-shadow: 0 0 0 2px white,
0 0 0 4px black;
}
点击扩展程序图标,弹出按钮
3.2 action逻辑
popup.html载入js脚本
<script src="popup.js"></script>
popup.js
初始化按钮颜色,按钮点击页面对背景颜色修改
// Initialize button with user's preferred color
let changeColor = document.getElementById("changeColor");
chrome.storage.sync.get("color", ({ color }) => {
changeColor.style.backgroundColor = color;
});
// When the button is clicked, inject setPageBackgroundColor into current page
changeColor.addEventListener("click", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: setPageBackgroundColor,
});
});
// The body of this function will be executed as a content script inside the
// current page
function setPageBackgroundColor() {
chrome.storage.sync.get("color", ({ color }) => {
document.body.style.backgroundColor = color;
});
}
需要 activeTab
权限允许程序临时访问当前页面, scripting
权限使用 executeScript
方法.
{
"name": "HelloWorld",
"description": "Build an Extension!",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["storage", "activeTab", "scripting"],
"action": {
"default_popup": "popup.html"
}
}
效果:点击白色按钮网页背景变色
3.2 在action添加图标
显示效果
{
"name": "HelloWorld",
"description": "Build an Extension!",
"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"
}
}
}
3.3 清单添加icon
效果
注意:
只能在网站中注入content scripts,不能在浏览器内部页面,如扩展程序页面中注入脚本。
官网原文
Extensions can not inject content scripts on internal Chrome pages like "chrome://extensions". Be sure to try out the extension on a real webpage like https://google.com.
4、users options
4.1 配置选项跳转页面
4.2 程序设计
选项跳转
跳转到此页面,在此页面切换颜色
返回可以切换背景颜色
4.3 程序实现
1、manifest.json
{
"name": "HelloWorld",
"description": "Build an Extension!",
"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"
}
2、options.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="button.css">
</head>
<body>
<div id="buttonDiv">
</div>
<div>
<p>Choose a different background color!</p>
</div>
</body>
<script src="options.js"></script>
</html>
options.js
let page = document.getElementById("buttonDiv");
let selectedClassName = "current";
const presetButtonColors = ["#3aa757", "#e8453c", "#f9bb2d", "#4688f1"];
// Reacts to a button click by marking the selected button and saving
// the selection
function handleButtonClick(event) {
// Remove styling from the previously selected color
let current = event.target.parentElement.querySelector(
`.${selectedClassName}`
);
if (current && current !== event.target) {
current.classList.remove(selectedClassName);
}
// Mark the button as selected
let color = event.target.dataset.color;
event.target.classList.add(selectedClassName);
chrome.storage.sync.set({ color });
}
// Add a button to the page for each supplied color
function constructOptions(buttonColors) {
chrome.storage.sync.get("color", (data) => {
let currentColor = data.color;
// For each color we were provided…
for (let buttonColor of buttonColors) {
// …create a button with that color…
let button = document.createElement("button");
button.dataset.color = buttonColor;
button.style.backgroundColor = buttonColor;
// …mark the currently selected color…
if (buttonColor === currentColor) {
button.classList.add(selectedClassName);
}
// …and register a listener for when that button is clicked
button.addEventListener("click", handleButtonClick);
page.appendChild(button);
}
});
}
// Initialize the page by constructing the color options
constructOptions(presetButtonColors);
TonaldOxiva 游客 2024-03-27 00:51 回复
Купить детские площадки в Кривом Роге можно без особых проблем.Универсальность тренажеров для улицы обусловлена тем, что человек работает исключительно с весом собственного тела, снижая нагрузки на суставы.
http://mixedarts.ru/013.html
http://mfk-lokomotiv.com.ua/news_arh.php?year=2016
http://fcmetalurg.com/season/metalurg-2/allmatches2/
До того ж на всі вироби виробник надає гарантійне обслуговування на протязі одного року.Игровой комплекс Сказка 12 из дерева уличный.