57

I'm using a listener in the background page to know when a tab is loaded:

chrome.tabs.onUpdated.addListener(function (tabId) { })

But the listener is fired twice: when the page has started loading, and when the page has finished.Is there a way to differentiate the two cases?

Preview
  • 35,317
  • 10
  • 92
  • 112
Omiod
  • 11,285
  • 11
  • 53
  • 59
  • To know when a tab **starts** loading, see https://stackoverflow.com/questions/19191679/chrome-extension-inject-js-before-page-load/19192010#19192010 – Pacerier Aug 10 '17 at 05:46

2 Answers2

102

Luckily have found the solution.

There is an additional parameter that holds the status value:

chrome.tabs.onUpdated.addListener(function (tabId , info) {
  if (info.status === 'complete') {
    // your code ...
  }
});

Status can be either loading or complete.

Preview
  • 35,317
  • 10
  • 92
  • 112
Omiod
  • 11,285
  • 11
  • 53
  • 59
  • 1
    Isn't ); missing at the end? – Lawand Aug 08 '13 at 13:34
  • 3
    PS Note this is good for background scripts. For content scripts, just use `window.onready` – Peter Ehrlich Mar 14 '14 at 03:06
  • 2
    @PeterEhrlich Problem with Window.onready is that it fires up as soon as init DOM is loaded. If you try for sites like gmail which keeps getting data, it fires immediately. – Volatil3 Apr 11 '16 at 03:40
  • How to know exactly which tab finished, as the info has just status completed. if user opened 3 tags one after other, theres no way of knowing which one actually finished first and which one last. @Balthazar – Soumyajit Dutta May 26 '20 at 15:07
  • 1
    I did it this way, but doesn't work for youtube. The site is still incomplete when trying to find elements. – Arturas M Jul 18 '20 at 20:22
  • 1
    @SoumyajitDutta the tabId parameter should help you here, to distinguish. using this param you can get the url of that tab – sktguha Oct 14 '20 at 14:58
29

I wanted a easier way to do this after opening a tab

function createTab (url) {
    return new Promise(resolve => {
        chrome.tabs.create({url}, async tab => {
            chrome.tabs.onUpdated.addListener(function listener (tabId, info) {
                if (info.status === 'complete' && tabId === tab.id) {
                    chrome.tabs.onUpdated.removeListener(listener);
                    resolve(tab);
                }
            });
        });
    });
}

so it would be

let tab = await createTab('http://google.com');
Chad Cache
  • 9,668
  • 3
  • 56
  • 48