Chrome Extension to Loop to Close Non-Selected Tabs
I've made this extension for Safari that closes inactive tabs on the current page
(var tabss = safari.application.activeBrowserWindow.tabs;
for (n=0; n<tabss.length; n++)
{
if(tabss[n] != safari.application.activeBrowserWindow.activeTab)
tabss[n].close();
}
)
I want to make the same for Chrome. But Chrome has a different way of doing things. I still want to run the loop on the index of tabs and close them if they aren't the selected tab. I've been able to get the length of the windows index but I don't know how to do a close tab loop that many times that will make sure not to close the selected tab. I have been able to get the length by doing this:
<html>
<head>
<script>
var targetWindow = null;
var tabCount = 0;
function start(tab) {
chrome.windows.getCurrent(getWindows);
}
function getWindows(win) {
targetWindow = win;
chrome.tabs.getAllInWindow(targetWindow.id, getTabs);
}
function getTabs(tabs) {
tabCount = tabs.length;
alert(tabCount);
}
// Set up a click handler so that we can merge all the windows.
chrome.browserAction.onClicked.addListener(start);
</script>
</head>
</html>
Gleaned from http://code.google.com/chrome/extensions/samples.html Merge Windows.
Now I want to run the loop but I can't figure out how to tell the loop not to close the selected tab. I was thinking of having the loop compare t开发者_运维知识库he looped tab to the tab ID of the selected window and it won't close that and move to the next tab index number in the loop.
Something like:
(
for (n=0; n<tabCount; n++)
{
if(chrome.tabs[n].id != tab.id)
chrome.tabs[n].remove();
}
)
But I don't know how to inject the current tabid as all the callback functions has this javascript hack/noob stumped. I can't introduce a variable from another function from what I understand.
This should do it:
// when a browser action is clicked, the callback is called with the current tab
chrome.browserAction.onClicked.addListener(function(curtab)
{
// get the current window
chrome.windows.getCurrent(function(win)
{
// get an array of the tabs in the window
chrome.tabs.getAllInWindow(win.id, function(tabs)
{
for (i in tabs) // loop over the tabs
{
// if the tab is not the selected one
if (tabs[i].id != curtab.id)
{
// close it
chrome.tabs.remove(tabs[i].id)
}
}
});
});
});
精彩评论