步驟 1:創(chuàng)建 manifest.json 文件
步驟 2:添加圖標(biāo)
步驟 3:創(chuàng)建 html 和代碼,開發(fā)拓展交互窗口或后臺服務(wù)或注入腳本
創(chuàng)建manifest.json
這個(gè)文件用于聲明插件項(xiàng)目的相關(guān)信息,不用多說,本插件使用的內(nèi)容格式如下:
{
"manifest_version": 3,
"name": "文檔助手",
"version": "0.1",
"description": "desc docs",
"icons": {//指定拓展插件的icon
"16": "icons/icon48.png",
"32": "icons/icon48.png",
"48": "icons/icon48.png",
"64": "icons/icon72.png",
"128": "icons/icon144.png"
},
"run_at": "document_idle",
"action": {//指定拓展插件的交互頁面
"default_popup": "html/menu.html"
},
"permissions": ["storage", "tabs"],//指定拓展程序需要瀏覽器哪些權(quán)限
"background": {
"service_worker": "js/server.js"http://指定拓展程序后臺服務(wù)的js,會在安裝后在后臺運(yùn)行
},
"content_scripts": [//匹配注入特定網(wǎng)頁的規(guī)則與腳本地址,可以在網(wǎng)頁加載完成后獲取網(wǎng)頁上下文執(zhí)行腳本
{
"matches": ["https://xxx.com/*"],
"js": ["js/inject.js"]
},
{
"matches": ["https://xxx.com/i/#/docs/*"],
"js": ["js/inject-path.js"]
}
]
}
通信
拓展插件也是一個(gè) html 小項(xiàng)目,拓展插件-服務(wù)腳本-目標(biāo)頁面,可以按照這樣的方式分為三端,在項(xiàng)目里開發(fā)三個(gè)js腳本,三者通過監(jiān)聽事件的方式通信,這樣進(jìn)行調(diào)用。
在需要和指定頁面通信時(shí),需要獲取目標(biāo)頁面的 tabId,規(guī)范寫法如下
注意,這里 query 傳入的回調(diào)是 function 函數(shù),不能傳入箭頭函數(shù),否則獲取不到 tabs(這個(gè)坑了好久),另外 background 腳本好像也無法獲取 tabs 信息。
function getTargetTabId(callback) {
console.log("getTargetTabId");
chrome.tabs.query({ currentWindow: true }, function (tabs) {
console.log("getTargetTabId", tabs);
for (var i = 0; i < tabs.length; i++) {
console.log("tabs", i, tabs[i]);
if (tabs[i].url && tabs[i].url.startsWith("https://xxx.com/")) {
callback && callback(tabs[i]);
return;
}
}
});
}
發(fā)送通信數(shù)據(jù),如果發(fā)送給指定 tab 網(wǎng)頁,則需要 tab 的 id,tab id獲取方式如上。
chrome.tabs.sendMessage(
request.tab.id,
{
cmd: "getToken",
},
function (response) {
console.log("server get response", response);
sendResponse(response);
}
);
添加監(jiān)聽
適用于監(jiān)聽來自其他端(拓展程序,后臺服務(wù)腳本,目標(biāo)網(wǎng)頁植入的腳本)發(fā)來的消息。
注意,這里如果無法立即執(zhí)行 sendResponse,則需要 return true,否則報(bào)錯
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(
sender.tab ? "from a content script:" : "from the extension",
request.cmd
);
if (request.cmd == "getToken") {
console.log("[server]sendMessage to tab:", request.tab.id);
chrome.tabs.sendMessage(
request.tab.id,
{
cmd: "getToken",
},
function (response) {
console.log("server get response", response);
sendResponse(response);
}
);
}
return true;
});
content_scripts
注入網(wǎng)頁的腳本可以使用網(wǎng)頁上下文環(huán)境,包括獲取document,獲取localStorage等等。
其他信息參考官方說明:
https://www.perplexity.ai/search/137e0395-1709-40c5-a94e-1f4cb05c18af?s=u