[英]How to close all tabs except the active one on demand with content script in chrome extension
我正在嘗試關閉除活動選項卡以外的所有選項卡。 我在商店中找到了擴展名: 關閉所有標簽。 我簡化了它,留下了我需要的功能。
清單.json:
{
"background": {
"persistent": false,
"scripts": [ "background.js" ]
},
"browser_action": {
"default_icon": "icons/128.png",
"default_title": "Close All Tabs"
},
"manifest_version": 2,
"name": "Close All Tabs",
"version": "1.1.1"
}
背景.js:
const closeAllTabs = function(thisTab) {
let querying = chrome.tabs.query({}, function(tabs){
for (let tab of tabs) {
console.log(tab.id);
console.log(thisTab.id);
if (tab.id !== thisTab.id) chrome.tabs.remove(tab.id);
}
// result with 2 tab:
// 50035
// 50035
// 50041
// 50035
});
}
chrome.browserAction.onClicked.addListener(function(thisTab) {
closeAllTabs(thisTab);
});
如果您單擊該圖標,該擴展程序將起作用,然后除活動選項卡之外的所有選項卡都將關閉。 我通過添加一個發送消息而不是點擊的內容腳本來改變這一點。
清單.json:
{
"background": {
"persistent": true,
"scripts": [ "background.js" ]
},
"permissions": ["background","tabs","<all_urls>","activeTab"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": true
}
],
"manifest_version": 2,
"name": "Close All Tabs",
"version": "1.1.1"
}
背景.js:
const closeAllTabs = function(thisTab) {
let querying = chrome.tabs.query({}, function(tabs){
for (let tab of tabs) {
console.log(tab.id);
console.log(thisTab.id);
if (tab.id !== thisTab.id) chrome.tabs.remove(tab.id);
}
// result with 2 tab:
// 50035
// undefined
// 50041
// undefined
});
}
chrome.runtime.onMessage.addListener(function(thisTab) {
closeAllTabs(thisTab);
});
內容.js:
chrome.runtime.sendMessage({});
但它不起作用(所有頁面都關閉)。 為什么當我點擊擴展圖標時一切正常。 而當我發送消息並運行該函數時,無法確定 thisTab.id(欠精細)?
onMessage的第一個參數是您發送的消息。 該選項卡位於第二個參數內:
chrome.runtime.onMessage.addListener(function(msg, sender) {
closeAllTabs(sender.tab);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.