gpt4 book ai didi

javascript - 扩展程序中每个 Chrome 选项卡的唯一 session

转载 作者:行者123 更新时间:2023-12-02 22:46:00 25 4
gpt4 key购买 nike

所以我对 JS 很陌生,这是我的第一个 Chrome 扩展。这非常简单。我在扩展栏中有一个切换开关。单击后,它会替换网站中的文本。再次单击时,它会恢复为原始文本。就目前而言,它的工作原理应该是这样的。我遇到的问题是当我打开新选项卡或窗口时,切换状态不会重置。这导致:

选项卡 1:切换已关闭

选项卡 1:点击切换切换已打开

标签2:打开,网页有原文

选项卡 2:点击切换切换已切换为关闭状态,因此没有任何反应

选项卡 2:点击切换切换为打开状态,最终替换文本

选项卡 2:点击切换切换已关闭,文本已恢复

选项卡 1:点击切换切换已打开,文本已打开,因此没有任何反应

你明白了。如果我再开一个新的寡妇也是一样的。我需要将切换状态保留在一页内,但在选项卡/窗口之间重置,因此每个选项卡/窗口只需单击一次即可切换到下一个状态。这是我所拥有的:

ma​​nifest.json

"manifest_version": 2,
"name": "Chrome Decolonized",
"icons": { "16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png" },
"description": "Replaces foreign names for tribes and locations in tribal homelands with the original names used by the indigenous people.",
"version": "1.0",
"background":
{
"scripts": ["background.js"]
},
"permissions": [
"activeTab"
],
"browser_action": {
"default_title": "(De)Colonize Toggle"
}
}

background.js


chrome.browserAction.onClicked.addListener(function(tab) {
if (clickit == 0){
chrome.tabs.executeScript({file:"content.js"}); //execute for this tab
clickit++;
//alert("Clickit was 0 and now is " + clickit);
}else if (clickit == 1){
chrome.tabs.executeScript({file:"colonized.js"}); // revert for this tab
clickit++;
//alert("Clickit was 1 and now is " + clickit);
}else{
chrome.tabs.executeScript({file:"content.js"}); //execute for this tab
clickit = 1;
//alert("Clickit was neither and now is " + clickit);
}

});

如有任何建议,我们将不胜感激。我已经搜索过答案,但没有找到与这个问题非常接近的内容。

最佳答案

您必须保留每个打开的选项卡的切换状态。

background.js

const state = {
loaded: {},
injected: {},
}

const toggleIn = ({id:tab_id}) => {
// toggle out: it's currently loaded and injected
if (state.loaded[tab_id] && state.injected[tab_id]) {
chrome.tabs.executeScript(tab_id, { file: 'content.js' });
state.injected[tab_id] = false;
}

// toggle in: it's loaded and needs injected
else if (state.loaded[tab_id] && !state.injected[tab_id]) {
chrome.tabs.executeScript(tab_id, { file: 'colonized.js' })
state.injected[tab_id] = true;
}

// fresh start in tab
else {
chrome.tabs.executeScript(tab_id, { file: 'content.js' })
state.loaded[tab_id] = true
state.injected[tab_id] = true
}

chrome.tabs.onUpdated.addListener(function(tabId) {
if (tabId === tab_id)
state.loaded[tabId] = false
})
}


chrome.browserAction.onClicked.addListener(function(tab) {
toggleIn({id: tab.id});
});

关于javascript - 扩展程序中每个 Chrome 选项卡的唯一 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com