Jeremy Toeman
Jeremy Toeman

Reputation: 81

Closing Tab in Chrome Extension

I have a function called in popup.html that creates a tab, inserts a mailto to trigger a local (or gmail) mail event. It's my desire for it to then close itself. I've tried numerous things, but it seems like I need something that does the equivalent of:

tabId = chrome.tabs.query(I DON'T KNOW!);
chrome.tabs.remove(tabId);

here's the current code:

var query = { active: true, currentWindow: true };
function callback(tabs) {
    var currentTab = tabs[0];
    console.log(currentTab);
}
chrome.tabs.remove(chrome.tabs.query(query, callback));

but it's not working.

if useful, here's how I create the tab (which does work as desired):

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        getTabs(tabs, function(full_mail_link){
          chrome.tabs.create({ url: full_mail_link });
        });
    });

any help would be greatly appreciated!

Upvotes: 4

Views: 10493

Answers (3)

AmineBmg
AmineBmg

Reputation: 51

this must be work:

chrome.tabs.getSelected(null, function(tab) {
 chrome.tabs.remove(tab.id);
 });

Upvotes: 5

Mouser
Mouser

Reputation: 13304

This should work:

//create the tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    getTabs(tabs, function(full_mail_link){
      chrome.tabs.create({ url: full_mail_link }, callBackOnCreate);
    });
});

function callBackOnCreate(tab)
{
     globalCreatedTab = tab.id;
}

chrome.tabs.query({'active': true}, function(tabs) {
      for (var i = 0; i < tabs.length; ++i)
      {
          if (tabs[i].id === globalCreatedTab)
          {
              chrome.tabs.remove(tabs[i].id, [optional callback]);
          }
      }

 });

Solution: use the query function with the callback and execute the remove function in the callback.

It looks like normal window.open and window.close() should also work, The tab-id is an integer or an array containing integers.

Upvotes: -1

Edwin Reynoso
Edwin Reynoso

Reputation: 1531

I don't know what your getTabs function does. Yet if you know how to find the tab id of the tab you want all you need to do is

chrome.tabs.remove(tabId, optionalCallback);

Upvotes: 8

Related Questions