Reputation: 25
i'm having a lot of trouble with Chrome Extensions, im trying to close all open tabs that do not contain a certain class.
This is the general idea of what i am trying to do, some of it is pseudo-code.
//background.js
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.query(function(tabs) {
chrome.tabs.sendMessage(tabs, {"message": "clicked_browser_action"});
});
});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "clicked_browser_action" ) {
for (var i = 0; i < request.length; i++) {
var existsClass = request[i].getElementByClass("someClass");
if (existClass === null) {
//TODO Close tab
}
}
}
}
);
Any help or suggestions would be appreciated.
Thanks!
Upvotes: 0
Views: 196
Reputation: 5118
Try this:
//background.js
chrome.browserAction.onClicked.addListener(function () { //when the extension's icon is pressed
chrome.tabs.query({},function(tabs) { // get all tabs
for (var i = tabs.length; i--;){ // loop through all tabs
chrome.tabs.executeScript(tabs[i].id,{code: //execute this code in each tab
"if (!document.querySelector(\".someClass\")) close();"});
// ^ if no element is found with the selected class, close the tab
}
});
});
You don't need a separate content script for that.
Upvotes: 0
Reputation: 77523
I'm assuming your second snippet is from a content script.
In that case, it's as simple as window.close()
, because you're in that tab's context. No need for Chrome APIs.
Upvotes: 1