Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get removed tabs Url in Chrome extension develop

I'm trying to make some Google Chrome extensions I want to remember the tab information that recently removed. But I got a problem. Every time I got the removed tabs information like URL, Title and so on with the method chrome.tabs.get ,but there is an error said that 'Error during tabs.get: No tab with id'.

I think this is because the tabs have removed before the tabs.get method get the tabs info. But how can i get recently removed tab URL?

This is my code:

chrome.tabs.onRemoved.addListener(getRemovedTabs);
function getRemovedTabs(tabId, removeInfo) {
    chrome.tabs.get(tabId, function (tab) {
        //do stuffs
    });
}
like image 622
Jack Zhang Avatar asked Sep 01 '12 11:09

Jack Zhang


1 Answers

The chrome.tabs.onRemoved event is triggered when the tab is removed, not when "it is about to get removed". There's no way to get information about a tab after it's removed.

Information must be collected before a tab is removed. The chrome.tabs.onUpdated event is the most convenient event for this:

// Background script
var tabToUrl = {};
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    // Note: this event is fired twice:
    // Once with `changeInfo.status` = "loading" and another time with "complete"
    tabToUrl[tabId] = tab.url;
});

chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
    do_stuff_with( tabToUrl[tabId] );

    // Remove information for non-existent tab
    delete tabToUrl[tabId];
});

Obviously, you're not restricted to storing only the URL in the tabToUrl object. Each tab type contains primitive values (booleans, integers and strings), so storing the tab object will not lead to severe memory consumption.
The properties may not be accurate though, because onUpdated is only triggered when the page (re)loads. If other properties are relevant, make sure that you also bind event listeners to the other chrome.tab events.

like image 86
Rob W Avatar answered Sep 22 '22 13:09

Rob W