xx55tt
xx55tt

Reputation: 283

How to close the current extension tab?

I'm trying to close the Options page of the extension. I have a Cancel button and I'm using this code:

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

When I'm trying to use it, it always gives this error:

Uncaught TypeError: Cannot call method 'getCurrent' of undefined

What's wrong with the code?

Upvotes: 24

Views: 32351

Answers (5)

T.Todua
T.Todua

Reputation: 56351

Only this worked for me:

chrome.tabs.query({ active: true }, function(tabs) {  
    chrome.tabs.remove(tabs[0].id);   
}); 

Upvotes: 3

xx55tt
xx55tt

Reputation: 283

I have time to continue my extension after a very long time. I checked the documentation again. So it was a inline script, that I had probably blocked with Content Security Policy in the manifest, because I hadn't read the documentation precisely.
Now Chrome blocks inline scripts by default, so I'll have to fix it anyway.

Upvotes: 1

martin
martin

Reputation: 96891

It works for me with one little fix:

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

Just make sure you're really running this code in options page of your extension and not just some HTML page, because chrome.tabs API is available only for extensions.

Upvotes: 38

Boris Smus
Boris Smus

Reputation: 8472

Most likely you're running your code from a content script, where chrome.tabs is undefined. If this is the case, you can instead send a message to the background page and have the background page (which has access to chrome.tabs) make the call.

Note that from a background page, you would use chrome.tabs.getSelected since getCurrent will return undefined.

Upvotes: 13

Mohamed Mansour
Mohamed Mansour

Reputation: 40149

In the options page, you can just do:

window.close()

If you wanted to use chrome.tabs.getCurrent, do you have tabs defined in the permissions section within the manifest?

Upvotes: 5

Related Questions