July 3, 2020

Chrome Extension: Close Current Tab

Introduction I've faced the challenge in a Chrome extension to close the current tab - and the chrome window if this Tab is the last one.

Standard answer

chrome.tabs.query({"active": true, "lastFocusedWindow": true}, function (tabs) {
chrome.tabs.remove(tabs[0]);
});
The drawback of this solution is that it won't close the Chrome window if it is the last tab to be closed.

My solution (close window if last tab)

/ ----------------------------------------------------------------------------------------------------------
function closeCurrentTab(){
// Close current tab and browser window if last tab
// chrome.tabs.remove will not close the window on last tab closure -> needs to check if single tab opened
chrome.tabs.query({
    //active: true,
    currentWindow: true
}, function(tabs)   {
    if (tabs.length > 1{
        chrome.tabs.query({
            active: true,
            currentWindow: true
        }, function(tabs)   {
        chrome.tabs.remove(tabs[0].id, function() { });
        });
    } else {
        chrome.windows.getCurrent(function(win) {
            chrome.windows.remove(win.id, function() { });
        });
    }       
});

No comments:

Post a Comment