使用vue開發瀏覽器chrome插件教程,及之間的消息通信

基本介紹

開發瀏覽器插件,首先需要先了解他的結構,瀏覽器擴展通常包括以下幾個部分

├── manifest.json
├── package.json
├── vite.config.js
├── src
├── background
│ └── index.js
├── content
│ └── content.js
├── icons
│ └── icon_16x16.png
│ └── icon_48x48.png
│ └── icon_128x128.png
├── popup
├── App.vue
├── index.html
├── main.ts
└── style.css

manifest.json:擴展的配置文件,是插件的入口文件

background.jsbackground 目錄:包含擴展的后臺腳本,它在插件安裝時就會加載,并且在瀏覽器運行期間始終保持活動狀態

content:在網頁中注入的腳本

popup:用戶界面部分,是插件彈框頁面

icons 是放置插件的 16、48、128 的 png 圖片

manifest.json 配置
{"manifest_version": 2,"name": "My Browser Extension","version": "1.0","background": {"scripts": ["background/index.js"]},"permissions": ["activeTab","storage"],"icons": {"16": "icon.png","48": "icon.png","128": "icon.png"},"content_scripts": [{"matches": ["<all_urls>"],"js": ["content/content.js"]}]
}
配置說明:

manifest_version:指定了manifest.json文件的版本號為2,表示遵循Manifest V2規范。
name:指定插件的名稱。
version:指定插件的版本號為"1.0.0"。
description:描述插件的簡要描述,這里是空字符串,可以填寫插件的功能介紹等信息。
author:指定插件的作者。
icons:包含不同尺寸的圖標文件路徑,用于在瀏覽器中顯示插件圖標。
options_page:指定插件的選項頁面為"options.html"。
page_action:配置頁面操作相關的信息,包括默認圖標、標題和彈出頁面。
content_security_policy:設置內容安全策略,限制了腳本和對象的來源,以增強安全性。
background:配置后臺頁面的持久性和后臺腳本文件路徑。
content_scripts:定義內容腳本,指定了腳本文件路徑、匹配的URL以及運行時機。
permissions:列出插件需要的權限,包括處理聲明式內容、標簽、活動標簽、Cookie、網絡請求、存儲等。
web_accessible_resources:指定可以從插件外部訪問的資源,這里是"fonts/*",表示可以訪問fonts文件夾下的所有資源。

創建項目
npm install -g @vue/cli
vue create my-browser-extension
cd my-browser-extension
消息通信

5種類型的JS對比
在這里插入圖片描述

一、popup.jsservice-worker.js

彈出頁面(popup.js) 和 背景腳本(service-worker.js) 之間的通信可以通過chrome.runtime.sendMessage 來實現

1.popup.jsservice-worker.js 發送消息

// service-worker.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {if (message.type === 'popupSendMessageToServiceWorker') {sendResponse({ success: true, message: 'service-worker.js收到消息' });}
});// popup.js
chrome.runtime.sendMessage({ type: 'popupSendMessageToServiceWorker' }, function(response) {console.log(response);  // 輸出從service-worker.js返回的數據
});

2.service-worker.jspopup.js 發送消息
背景腳本(service-worker.js)向彈出頁面(popup.js) 發送消息

// popup.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {if (message.type === 'serviceWorkerSendMessageToPopup') {sendResponse({ success: true, message: 'popup.js收到消息' });}
});// service-worker.js
chrome.runtime.sendMessage({type: 'serviceWorkerSendMessageToPopup'}, function (response) {console.log(response);  // 輸出從popup.js返回的數據
})
二、content.jsservice-worker.js

content.jsservice-worker.js 通常通過 chrome.runtime.sendMessagechrome.tabs.sendMessage 進行消息傳遞。

1.content.jsservice-worker.js 發送消息

// service-worker.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {if (message.type === 'contentSendMessageToServiceWorker') {sendResponse({ success: true, message: 'service-worker.js收到消息' });}
});// content.js
chrome.runtime.sendMessage({ type: 'contentSendMessageToServiceWorker' }, function(response) {console.log(response);
});

2.service-worker.jscontent.js 發送消息

//manifest.json 如需使用 tabs API,請在擴展程序manifest中聲明 "tabs" 權限。
{"permissions": ["tabs"]
}// service-worker.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {chrome.tabs.sendMessage(tabs[0].id, { greeting: 'Hello from background!' }, function (response) {console.log(response);  // 輸出從content.js返回的數據})
})// content.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {if (message.greeting) {console.log(message.greeting);  // 輸出: Hello from background!sendResponse({ response: 'Message received!' });}
});
三、content.jspopup.js

content_scriptspopup 主動發消息的前提是 popup 必須打開!否則需要利用 background 作中轉。

如果 backgroundpopup 同時監聽,那么它們都可以同時收到消息,但是只有一個可以 sendResponse ,一個先發送了,那么另外一個再發送就無效

使用和二的一樣

// content.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {chrome.tabs.sendMessage(tabs[0].id, { greeting: 'Hello from background!' }, function (response) {console.log(response);  // 輸出從popup.js返回的數據})
})// popup.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {if (message.greeting) {console.log(message.greeting);  // 輸出: Hello from background!sendResponse({ response: 'Message received!' });}
});
四、通過 chrome.storage 共享數據

有時候可能需要在多個部分之間共享數據,chrome.storage 是一個跨腳本的存儲機制,可以讓背景腳本、彈出頁面和內容腳本共享數據。這個類似于網頁中的local storage,很好理解

存儲數據:

//manifest.json 如需使用 Storage API,請在擴展程序manifest中聲明 "storage" 權限。
{"permissions": ["storage"]
}// background.js
// service-worker.js存儲數據
chrome.storage.local.set({ key1: 'value1' }, function () {console.log('Data saved!');
});
chrome.storage.local.set({ key2: true, key3: {key4: 'value4'} }, function () {console.log('Data saved!');
});

讀取數據:

// popup.js
chrome.storage.local.get('key1', function (result) {console.log('result is ' + JSON.stringify(result));console.log('Value currently is ' + result.key1);
});
chrome.storage.local.get(['key2'], function (result) {console.log('result is ' + JSON.stringify(result));console.log('Value currently is ' + result.key2);
});
chrome.storage.local.get(['key1','key2'], function (result) {console.log('result is ' + JSON.stringify(result));console.log('Value currently is ' + result.key2);
});
chrome.storage.local.get({key3: {} }, function (result) {console.log('result is ' + JSON.stringify(result));console.log('Value currently is ' + result.key3.key4);
});
chrome.storage.local.get({key5: true , key6:false}, function (result) {console.log('result is ' + JSON.stringify(result));console.log('Value currently is ' + result.key5 + ',' + result.key6);
});

刪除數據:

//刪除數據
chrome.storage.local.remove(['key1'], function() {console.log('Key1 removed successfully.');
});

清除所有的數據:

//清除所有數據
chrome.storage.local.clear(function() {console.log('All data cleared.');
});

監聽數據變化:

//content.js
// 監聽存儲變化(兩種方法都可以)
//chrome.storage.local.onChanged.addListener(function(changes) {
//    console.log('Storage area "local" has changed');
//    console.log(changes);
//});chrome.storage.onChanged.addListener(function(changes, area) {if (area === 'local') {console.log('Storage area "local" has changed');console.log(changes);}
});setTimeout(function (){chrome.storage.local.set({ key2: false }, function () {console.log('Data saved!');});
},5000)
五、使用 chrome.runtime.connect 和長連接

除了單次消息發送接收,chrome.runtime.connect 可以創建一個持久的連接,適用于需要長期通信的場景。

1.popup.jsservice-worker.js 長連接

// service-worker.js
chrome.runtime.onConnect.addListener(function(port) {console.log('Connected:', port.name);port.onMessage.addListener(function(msg) {if (msg.action === 'getUserInfo') {// 模擬從后臺獲取用戶信息const userInfo = { name: 'John Doe', age: 30 };port.postMessage({ data: userInfo });}});port.onDisconnect.addListener(function() {console.log('Port disconnected');});
});// popup.js
let port = chrome.runtime.connect({ name: 'popup' });
// 請求獲取用戶信息
port.postMessage({ action: 'getUserInfo' });
// 監聽來自service-worker.js的消息
port.onMessage.addListener(function(msg) {console.log('Received user info:', msg.data);
});

2.content.jspopup.js 長連接

// popup.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {let port = chrome.tabs.connect(tabs[0].id, {name: 'test-connect'});port.postMessage({question: '你是誰啊?'});port.onMessage.addListener(function(msg) {alert('收到消息:'+msg.answer);if(msg.answer && msg.answer.startsWith('我是')){port.postMessage({question: '哦,原來是你啊!'});}});
});// content.js
chrome.runtime.onConnect.addListener(function(port) {console.log(port);if(port.name === 'test-connect') {port.onMessage.addListener(function(msg) {console.log('收到長連接消息:', msg);if(msg.question === '你是誰啊?') port.postMessage({answer: '我是容易摔倒的豬!'});});}
});

實現三方長連接方式:

content.jsservice-worker.js 通過 chrome.runtime.connect 建立連接。
popup.js 也與 service-worker.js 進行通信。
service-worker.js 作為中介,協調 content.jspopup.js 的消息。

六、插件使用限制

1、content.js的腳本限制,在manifest.json中的content_scripts設置matches中執行的域名。

  "content_scripts": [{"js": ["js/content.js"],"matches": ["http://wangpu.taobao.com/*", "https://wangpu.taobao.com/*", "http://myseller.taobao.com/*", "https://myseller.taobao.com/*"],"run_at": "document_idle"}]

2、插件的popup頁面是否顯示
background.js中通過 window.chrome.declarativeContent.onPageChanged.addRules添加域名限制。

window.chrome.runtime.onInstalled.addListener(function () {window.chrome.declarativeContent.onPageChanged.removeRules(undefined, function () {window.chrome.declarativeContent.onPageChanged.addRules([{conditions: [new window.chrome.declarativeContent.PageStateMatcher({pageUrl: { urlContains: 'wangpu.taobao.com' }})],actions: [new window.chrome.declarativeContent.ShowPageAction()]}])})
})

window.chrome.declarativeContent是Chrome瀏覽器擴展程序中用于定義內容腳本的API。其中,urlContains、urlMatches和urlPrefix是用于匹配網頁URL的條件。

  • urlContains:表示URL包含指定的字符串時條件匹配。例如,如果指定urlContains: ‘example’,則只有當網頁URL中包含"example"時條件才會匹配。
  • urlMatches:表示URL匹配指定的正則表達式時條件匹配。例如,如果指定urlMatches: > ‘https://www.example.com/*’,則只有當網頁URL以"https://www.example.com/"開頭時條件才會匹配。
  • urlPrefix:表示URL以指定的字符串開頭時條件匹配。例如,如果指定urlPrefix: ‘https://example.com’,則只有當網頁URL以"https://example.com"開頭時條件才會匹配。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/89297.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/89297.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/89297.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

論文筆記(八十八)MLCVNet: Multi-Level Context VoteNet for 3D Object Detection

MLCVNet: Multi-Level Context VoteNet for 3D Object Detection 文章概括摘要I. 引言2. 相關工作2.1. 基于點云的 3D 目標檢測2.2. 上下文信息 3. 方法3.1. VoteNet3.2. PPC 模塊3.3. OOC 模塊3.4. GSC 模塊 4. 結果與討論4.1. 數據集4.2. 訓練細節4.3. 與最先進方法的比較4.4…

Redis初識第四期----Hash的命令和應用場景

首先為了區分Redis的鍵值對存儲的key-value&#xff0c;Hash中的鍵值對稱為field-value。 命令 1.Hset Hset key field value [field value] 返回值為設置成功的field-value的個數。 2.Hget Hget key field 返回為value 3.Hexists Hexists key field 判斷是否存在&a…

【大數據技術棧】數據管理范疇常用大數據技術棧

一、技術棧分層架構 大數據技術棧通常分為四個核心層級&#xff1a; 數據采集層 負責多源異構數據的實時/批量采集 日志采集&#xff1a; F l u m e Flume Flume、 L o g s t a s h Logstash Logstash消息隊列&#xff1a; K a f k a Kafka Kafka、 R a b b i t M Q RabbitMQ …

安全左移(Shift Left Security):軟件安全的演進之路

文章目錄 一、背景&#xff1a;傳統安全的尷尬處境二、安全左移&#xff1a;讓安全成為開發的“第一等公民”三、安全左移的關鍵實施階段1. 需求階段&#xff1a;嵌入安全需求建模2. 設計階段&#xff1a;威脅建模與架構審計3. 編碼階段&#xff1a;安全編碼規范與靜態分析4. 構…

固定債可以賣call嗎

我們都知道如果持有tlt&#xff0c;可以賣call來賺取時間價值&#xff0c;如果我買固定到期的美債而不是etf&#xff0c;有類似的操作嗎&#xff0c;我可以賣call嗎 以下是關于直接持有固定到期美債并嘗試賣出看漲期權的詳細分析&#xff1a; 一、直接持有美債與ETF&#xff08…

fish安裝node.js環境

為什么強調fish shell&#xff0c;因為fish shell的緣故&#xff0c;不能直接執行node.js官網的命令 好的&#xff0c;您遇到了一個非常典型且重要的問題。請仔細閱讀我的分析&#xff0c;這能幫您徹底解決問題。 問題診斷 您看到的所有錯誤&#xff0c;歸根結底有兩個核心原…

記一次Ubuntu22安裝MongoDB8并同步本地數據過程

1. 效果展示 2. 安裝MongoDB 8 根據官方文檔https://www.mongodb.com/zh-cn/docs/manual/tutorial/install-mongodb-on-ubuntu/一頓操作即可 2.1 配置微調支持遠程訪問 修改配置文件,默認/etc/mongod.conf # network interfaces net:port: 27017bindIp: 0.0.0.02.2 新增adm…

HarmonyOS應用開發高級認證知識點梳理 (三)狀態管理V2裝飾器核心規則

以下是針對HarmonyOS應用開發高級認證備考的?狀態管理V2裝飾器核心規則?知識點系統梳理&#xff1a; 一、核心裝飾器分類與功能 1. ?組件聲明裝飾器? ComponentV2? (1)基礎定義與限制 功能定位? 用于裝飾自定義組件&#xff0c;啟用V2狀態管理能力&#xff0c;需配…

SAP資產記賬相關業務成本中心為空的問題

用戶在資產記賬時&#xff0c;發現字段“成本中心”是空且為灰色的&#xff0c;并沒有顯示資產對應的成本中心&#xff0c;如下圖所示&#xff1a; 首先&#xff0c;關于資產購置記賬的相關業務&#xff0c;成本中心要不要顯示&#xff1f;其實是可以不顯示的&#xff0c;它是來…

智源大會AI安全論壇:深挖風險紅線,探討應對措施

6月7日&#xff0c;在與安遠AI聯合主辦的智源大會“AI安全論壇”上&#xff0c;來自MIT、清華、復旦、人大、智源、多倫多大學、新加坡管理大學、Redwood Research、瑞萊智慧和安遠AI 的學者與技術專家同臺&#xff0c;以“AI安全”為核心議題&#xff0c;從主旨報告&#xff0…

電機控制的一些筆記

1. 電角度和機械角度 電角度 機械角度 * 磁極對數 機械角度就是實際的空間幾何角度&#xff0c;范圍是0-360 https://blog.csdn.net/leekay123/article/details/108655482 https://www.bilibili.com/video/BV11Q4y1Y7kR/?spm_id_from333.788.recommend_more_video.1&vd…

c#手動編譯

一、配置環境變量 點擊環境變量&#xff0c;在用戶變量的path進行新建&#xff0c;點擊編輯 點擊新建 點擊新建 添加文件目錄 這是我的可能不一樣&#xff0c;C:\Windows\Microsoft.NET\Framework64\v4.0.30319 輸入 點擊確定&#xff0c;就可以了 二、建立cs文件 代碼實例…

pcap流量包分析工具設計

在復雜的網絡世界中&#xff0c;數據包是信息的載體&#xff0c;但也可能成為風險的源頭。無論是開發者調試接口&#xff0c;還是安全人員排查異常&#xff0c;都需要一個能夠看透數據本質的“眼睛”。然而&#xff0c;專業的網絡分析工具往往過于復雜&#xff0c;不適合快速定…

Qt 安裝與項目創建

一、Qt 介紹 1. Qt是什么&#xff1f; Qt是一個跨平臺的 C 開發庫&#xff0c;主要用來開發圖形用戶界面&#xff08;Graphical User Interface&#xff0c;GUI&#xff09;程序&#xff0c;當然也可以開發不帶界面的命令行&#xff08;Command User Interface&#xff0c;CU…

基于注意力機制的方法預測的體重

我們有一些已知的身高&#xff08;作為鍵 K K K&#xff09;和對應的體重&#xff08;作為值 V V V&#xff09;。現在&#xff0c;我們想使用一種基于注意力機制的方法來“查詢”一個特定身高&#xff08;比如 170cm&#xff09;對應的體重。雖然這通常不是注意力機制的典型…

Modbus TCP 進階:基于以太網的遠程設備控制(一)

Modbus TCP 基礎回顧 ** 在工業自動化領域&#xff0c;Modbus TCP 是一種廣泛應用的通信協議&#xff0c;它基于以太網&#xff0c;為設備之間的通信搭建了橋梁&#xff0c;實現了遠程設備的高效控制。Modbus TCP 是 Modbus 協議家族中的一員&#xff0c;它在傳統 Modbus 協議…

linux魔術字定位踩內存總結

0,數據被改寫時我們需要怎么定位,我們首先需要確認數據是邏輯上被改寫還是踩內存被改寫的。 1,當數據被踩時,也就是出現數據異常時,并且可以穩定復現時,我們確認時踩固定內存時,我們可以使用魔術字定位問題。 代碼舉例查看確認。 #include <stdio.h> #include…

淺談Docker Kicks in的應用

正因為傳統部署的麻煩&#xff0c;我們希望減少整個安裝過程&#xff0c;將其簡單化&#xff0c;以下介紹兩個思路&#xff1a; 思路一&#xff1a;安裝 Docker 后安裝 Ghost&#xff0c;并且直接暴露 80 端口&#xff0c;此時所有請求由 Docker 內的 Express 服務器處理&…

【Rust + Actix Web】現代后端開發:從零構建高并發 Web 應用

目錄 項目概述環境準備項目創建與依賴配置系統架構設計核心代碼實現1. 數據庫模型 (src/models.rs)2. 應用狀態管理 (src/state.rs)3. 核心業務邏輯 (src/handlers.rs)4. 主應用入口 (src/main.rs) 高并發優化策略1. 異步處理模型2. 連接池配置優化3. 緩存策略設計 性能測試結果…

2025java面試題整理通俗易懂好記

一、Java 基礎 1. JVM 相關 Q&#xff1a;什么情況下會發生棧內存溢出&#xff1f; A&#xff1a;就像食堂打飯窗口前排隊&#xff0c;隊伍太長&#xff08;方法調用層級太深&#xff09;&#xff0c;或者每個人占的位置太大&#xff08;局部變量太多&#xff09;&#xff0c;…