在JavaScript 中偵測Chrome 擴充程式安裝
在建置Chrome 擴充功能時,可能有必要確定該擴充功能是否是從外部JavaScript 腳本。這有助於根據擴充功能的存在來自訂 Web 內容。
根據 Chrome 文檔,可以透過從網站到擴充功能傳遞訊息來實現此目的。
程式碼實作
在擴充功能的background.js(或任何其他非內容腳本)檔案中,新增一則訊息監聽器:
chrome.runtime.onMessageExternal.addListener( function(request, sender, sendResponse) { if (request) { if (request.message) { if (request.message == "version") { sendResponse({version: 1.0}); } } } return true; } );
此監聽器將從網站接收訊息。
從網站的腳本中,向擴充功能的 ID 傳送訊息:
var hasExtension = false; chrome.runtime.sendMessage(extensionId, { message: "version" }, function (reply) { if (reply) { if (reply.version) { if (reply.version >= requiredVersion) { hasExtension = true; } } } else { hasExtension = false; } } );
檢查 hasExtension 變數以決定是否安裝了擴充功能。
Manifest Configuration
請記得向manifest.json 新增條目文件,指定允許向擴展發送訊息的網域:
"externally_connectable": { "matches": ["http://mylocalhostextensiontest/*", "http://*:*/*"] },
非同步性質與錯誤處理
請注意,訊息傳遞機制是非同步的,因此您可能需要在程式碼中處理此問題。
此外,如果未安裝或停用擴充程序,chrome.runtime.sendMessage 將拋出例外。在這種情況下,請在發送訊息後檢查 chrome.runtime.lastError:
if (chrome.runtime.lastError) { // Handle the error here... }
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3