[英]How to close all tabs except the active one on demand with content script in chrome extension
I'm trying to close all tabs except the active one.我正在尝试关闭除活动选项卡以外的所有选项卡。 I found the extension in the store: Close All Tabs .
我在商店中找到了扩展名: 关闭所有标签。 I simplified it leaving the function I needed.
我简化了它,留下了我需要的功能。
manifest.json:清单.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"
}
background.js:背景.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);
});
The extension works if you click on the icon, then all tabs except the active one will close.如果您单击该图标,该扩展程序将起作用,然后除活动选项卡之外的所有选项卡都将关闭。 I changed this by adding a content script that sends a message instead of a click.
我通过添加一个发送消息而不是点击的内容脚本来改变这一点。
manifest.json:清单.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"
}
background.js:背景.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);
});
content.js:内容.js:
chrome.runtime.sendMessage({});
But it doesn't work(all pages close).但它不起作用(所有页面都关闭)。 Why when I click on the extension icon everything works.
为什么当我点击扩展图标时一切正常。 And when I send a message and run the function, thisTab.id cannot be determined (underfined)?
而当我发送消息并运行该函数时,无法确定 thisTab.id(欠精细)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.