主要介绍content_scripts、action(popup)、devtools_page的作用,它们之间如何通信?列举了一些常见的api。
content_scripts:
说明: 与网页共享document、sessionStorage、localStorage、cookie(100版本实测可以共享,AI说105+不能共享)
,可读取、修改dom,变量不共享,无法读取网页window、元素等下面自定义的参数。
主要作用: 监听网页事件等一些交互,做事件对应动作。
manifest.json配置:
js
"permissions": [
"activeTab",
"tabs",
"notifications",
"scripting",
"storage",
"debugger",
"extension",
"contextMenus",
"proxy"
],
"host_permissions": [
"<all_urls>"
],
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"content/index.js" //加载的js文件
],
"run_at": "document_idle" //DOM和子资源加载完成后执行
}
]
通信:
与页面通信:
js
//接收信息
window.addEventListener('message', (event) => {
console.log(event.data);
});
//发送信息
window.postMessage({
type: 'extension messsage',
data: {test: ''}
}, '*');
与background、action(popup)、devtools_page之间的通信:
js
//发送信息(三个都会收到信息):
chrome.runtime.sendMessage({ page: 'content', params: 'ok' })
//其它三个通过下面方法发送消息给content_scripts
chrome.tabs.sendMessage(curTabId, params);
//接收信息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log('content listen', request);
//返回给sendMessage
sendResponse({ page: 'content', res: 'receive ok' });
return true;
});
background
说明: background是 Chrome 扩展的核心组件,它持续运行以管理扩展的核心功能,即使没有打开扩展的弹出窗口或内容脚本也在工作。(摘自AI),其实就是运行在后台的一个js文件,类似我们的worker。
作用: 用于计算比较耗时的任务、协调各组件通信,定时运行一些任务。v3版本的background如果长时间空闲需要重新唤醒。可以在网页中注入js代码执行(类似于在控制台执行一样)。
manifest.json配置:
js
"background": {
"service_worker": "background/index.js",
"type": "module" //支持es模块
},
向网页中注入js代码
js
await chrome.scripting.executeScript({
target: { tabId },
world: "MAIN", //执行环境
func, //函数
args, //函数参数
}, (result) => {
if (chrome.runtime.lastError) {
console.warn("执行失败:", chrome.runtime.lastError);
}
});
获取tabId
js
// tab更新
chrome.tabs.onUpdated.addListener((tabId) => {});
// 切换tab
chrome.tabs.onActivated.addListener(({ tabId, windowId }) => {});
创建上下文菜单
js
// 创建上下文菜单
chrome.contextMenus.create({
id: "customMenuItem",
title: "标题",
});
//点击菜单执行
chrome.contextMenus.onClicked.addListener(async(info, tab) => {
if (info.menuItemId === "customMenuItem") {
}
});
通信
与content_scripts、action(popup)、devtools_page之间的通信:
js
//发送信息action(popup)、devtools_page(两个都会收到信息):
chrome.runtime.sendMessage({ page: 'background', params: 'ok' })
//发送消息给content_scripts
chrome.tabs.sendMessage(curTabId, params);
//接收信息
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log('background listen', request);
//返回给sendMessage
sendResponse({ page: 'background', res: 'receive ok' });
return true;
});
action
说明: 插件的视图,右上角点击插件显示一个网页视图。
主要作用: 点击插件显示一个网页视图,可用于设置插件配置和需要用到视图交互功能时等,和background一样也可以注入js代码到网页执行,使用的较少,关闭网页生命周期就消失了。
manifest.json配置:
js
"action": {
"default_title": "标题",
"default_popup": "popup/index.html"
},
通信:
和background方式一样
devtools_page
说明: 控制台相关的功能。
主要作用: 一般用于调试,如打开源码文件、跳转到函数定义位置、监听网络请求等,关闭控制台后生命周期就消失了。
manifest.json配置:
js
"devtools_page": "devtools/index.html",
控制台标签页创建一个视图
js
chrome.devtools.panels.create(
"React Tools",
"",
"devtools/devIndex.html"
);
其他
js
// 获取当前窗口的tabId
chrome.devtools.inspectedWindow.tabId;
// 打开资源文件
chrome.devtools.panels.openResource(
path, //路径
row, //行号
col, //列号
resFunc, //打开后返回函数
);
// 获取所有资源文件
chrome.devtools.inspectedWindow.getResources(resources) => {});
// 监听请求
chrome.devtools.network.onRequestFinished.addListener(request => {
// 有新的请求文件就重新获取资源文件
if((request?._resourceType ?? 'script') === 'script') {
}
});
// 同eval,再控制台执行js函数
chrome.devtools.inspectedWindow.eval('');
通信:
和background、action方式一样