Reputation: 21
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:
{
"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:
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:
{
"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:
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:
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)?
Upvotes: 0
Views: 812