Llamageddon
Llamageddon

Reputation: 3526

How can I open a tab without loading it in a Google Chrome extension?

The only thing I could think of was using chrome.tabs.discard, and below is my current code:

var test_button= document.getElementById('test_button');
test_button.onclick = function(element) {
    var to_load = {"url": "https://stackoverflow.com", "active": false, "selected": false};
    chrome.tabs.create(to_load, function(tab) {
        chrome.tabs.discard(tab.id);
    });
};

However, rather than preventing this page from loading, calling chrome.tabs.discard before it's loaded results in Chrome replacing it with about:blank.

The only "solution" I found was to wait for the tab to load, but waiting for it to load before unloading it defeats the purpose, especially if I'm opening a large amount of tabs at once.

Any help would be appreciated.

Upvotes: 2

Views: 1008

Answers (1)

Llamageddon
Llamageddon

Reputation: 3526

The solution is to only call chrome.tabs.discard on the tab after its URL value has updated, such as:

var tabs_to_unload = {}
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, changedTab) {
    if (tabs_to_unload[tabId] == true) {
        // We can only discard the tab once its URL is updated, otherwise it's replaced with about:empty
        if(changeInfo.url) {
            chrome.tabs.discard(tabId);
            delete tabs_to_unload[tabId];
        }
    }
});

var test_button= document.getElementById('test_button');
test_button.onclick = function(element) {
    var to_load = {"url": "https://stackoverflow.com", "active": false, "selected": false};
    chrome.tabs.create(to_load, function(tab) {
        tabs_to_unload[tab.id] = true;
    });
};

In my case, the exact code was a bit different, as I was performing these actions from within a popup, and the variables and listeners registered by its script only lived as long as the popup, but the principle behind it was the same.

Upvotes: 5

Related Questions