[英]turn on and off chrome extension
我正在開發一個 chrome 擴展程序,這個擴展程序在瀏覽器操作中有 2 個圖標(開和關); 基本上,當它在后台使用chrome.tabs.executeScript(tab.id,{file:"script.js",function(){});
在后台執行 script.js(注入文件:script.js chrome.tabs.executeScript(tab.id,{file:"script.js",function(){});
我有問題無法關閉它! 我曾嘗試在 background.js 和 script.js 之間使用消息通信,但這也不起作用。
如果我理解正確,您的擴展程序應該有兩種狀態,打開和關閉。 單擊擴展圖標可打開/關閉它。
在這種情況下,您應該使用存儲,以便擴展程序知道它處於什么狀態。因此,在單擊事件中,請使用以下內容:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.storage.sync.get('state', function(data) {
if (data.state === 'on') {
chrome.storage.sync.set({state: 'off'});
//do something, removing the script or whatever
} else {
chrome.storage.sync.set({state: 'on'});
//inject your script
}
});
});
請注意,這發生在擴展程序/瀏覽器級別並將應用於所有選項卡,因此您可能需要更復雜的內容來記錄選項卡 ID 和狀態。
然后,您可以選擇始終運行內容腳本並在執行某些操作之前檢查開/關狀態,或者注入和刪除腳本。 我不確定你是否刪除了腳本。 根據腳本的作用,您可能只想刷新頁面(即,如果您的腳本與 DOM 混淆並且您想在關閉擴展程序時撤消該操作)。
背景.js
var enable=false;
chrome.browserAction.onClicked.addListener(function (tab) {
enable = enable ? false : true;
if(enable){
//turn on...
chrome.browserAction.setIcon({ path: 'icon.png' });
chrome.browserAction.setBadgeText({ text: 'ON' });
chrome.tabs.executeScript(null, { file: 'content.js' });
}else{
//turn off...
chrome.browserAction.setIcon({ path: 'disable.png'});
chrome.browserAction.setBadgeText({ text: '' });
}
});
為了添加@david-gilbertson 所說的使某些選項卡處於活動狀態和非活動狀態的內容,我在此處創建了該功能。 我還添加了一些用於刪除和添加選項卡到數組的功能。 享受!
function addTab(array, new_tab_id)
{
array.push(new_tab_id);
//then call the set to update with modified value
chrome.storage.sync.set({
active_tabs:array
}, function() {
console.log("added tab");
});
}
function removeTab(array, rem_tab_id)
{
const index = array.indexOf(rem_tab_id);
if (index > -1) {
array.splice(index, 1);
}
//then call the set to update with modified value
chrome.storage.sync.set({
active_tabs:array
}, function() {
console.log("removed tab");
});
}
chrome.browserAction.onClicked.addListener(function (tab) {`enter code here`
chrome.storage.sync.get({active_tabs : []}, function(data) {
if (data.active_tabs.includes(request.tab_id)) {
removeTab(data.active_tabs, request.tab_id)
console.log("Turned Off ".concat(request.tab_id))
document.removeEventListener("mousemove", highlightCurrentHover, false);
} else {
addTab(data.active_tabs, request.tab_id)
console.log("Turned On ".concat(request.tab_id))
document.addEventListener('mousemove', highlightCurrentHover, false);
}
});
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.