Close all tabs and *active last*

Talk about add-ons and extension development.
Post Reply
Yaron10
Posts: 472
Joined: July 5th, 2011, 6:32 am

Close all tabs and *active last*

Post by Yaron10 »

Code: Select all

async function closeAllTabs(activeTab)
{
    const tabs = await browser.tabs.query({ currentWindow: true, active: false });
    for (const tab of tabs)
        browser.tabs.remove(tab.id);

    browser.tabs.remove(activeTab.id);  // Close the active tab last so that it would be first in the Recently Closed list.
}

browser.browserAction.onClicked.addListener(closeAllTabs);
How do I make sure the active tab is closed last? With the code above, it works intermittently.
morat
Posts: 6404
Joined: February 3rd, 2009, 6:29 pm

Re: Close all tabs and *active last*

Post by morat »

I would do something like so.

Code: Select all

chrome.tabs.query({currentWindow: true}, function (tabs) {
  var ids = [];
  for (var i = 0; i < tabs.length; i++) {
    if (tabs[i].active == false) {
      ids.push(tabs[i].id);
    }
  }
  for (var i = 0; i < tabs.length; i++) {
    if (tabs[i].active == true) {
      ids.push(tabs[i].id);
    }
  }
  for (var i = 0; i < ids.length; i++) {
    chrome.tabs.remove(ids[i], function () {});
  }
});
Try adding a delay if there is a problem.
Yaron10
Posts: 472
Joined: July 5th, 2011, 6:32 am

Re: Close all tabs and *active last*

Post by Yaron10 »

@morat,

Thank you. I appreciate your help.

I posted earlier on stackoverflow and then remembered this forum I hadn't visited for a long time. :)
Post Reply