CYB
CYB

Reputation: 421

Chrome Extension: Tab Listener onSelectionChanged

Got some problems with the chrome.tabs.onSelectionChanged.addListener. Everything works good, till the whole window is closed. Then this listener is triggered...for whatsoever reason. For me it's kinda buggy, but anyway:

On this listener, I'm working with the chrome.tabs.get function. And this function is throwing an error in the moment of windows close:

Error during tabs.get: No tab with id: 70.

This makes sense. The tab does no longer exist in this moment. Anyone did already had a way to work around this? One possible reason would be to remove the listener on window close. But sadly, the removeListener doesnt work (if anyone knows how to remove, I'm grateful).

Best

EDIT 1.1: Modified function from serg's approach (thx for that on this way):

First i tried to only catch the tabs of the actual window with: chrome.windows.getCurrent. But this function doesn't return the windows.tabs array. So I first read out the current windows.id and only loop through the tabs of this window.

function ensureTabExists(tabId, callback) {
    chrome.windows.getCurrent(function(windows) {
        var exists = false;
        windowsId=windows.id;
        chrome.windows.getAll({populate: true}, function(windows){
            loop:
            for(var w=0;w<windows.length;++w) {
                if (windows[w].id == windowsId) {
                    for(var t=0;t<windows[w].tabs.length;++t){
                        if(windows[w].tabs[t].id == tabId) {
                            exists = true;
                            break loop;
                        }
                    }
                }
            }
            if(exists && callback) {
                callback();
            } 
        });
    });
}

Upvotes: 1

Views: 1587

Answers (2)

serg
serg

Reputation: 111265

You can loop through all tabs in all windows and check if it still exists:

function ensureTabExists(tabId, callback) {
    chrome.windows.getAll({populate: true}, function(windows){
        var exists = false;
        loop:
        for(w=0;w<windows.length;w++) {
            for(t=0;t<windows[w].tabs.length;t++){
                if(windows[w].tabs[t].id == tabId) {
                    exists = true;
                    break loop;
                }
            }
        }
        if(exists && callback) {
            callback();
        } 
    });
}

//usage
chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo) {
    ensureTabExists(tabId, function(){
        //this code will run only if tab exists
    });
});

Upvotes: 2

Boris Smus
Boris Smus

Reputation: 8472

Use the chrome.window.onRemoved API to track when windows have closed. That way you can handle the window closing case more gracefully.

Upvotes: 0

Related Questions