Chrome extensions : How to know when a tab has finished loading, from the background page

Google Chrome

Google Chrome Problem Overview


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?

Google Chrome Solutions


Solution 1 - Google Chrome

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.

Solution 2 - Google Chrome

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');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmiodView Question on Stackoverflow
Solution 1 - Google ChromeOmiodView Answer on Stackoverflow
Solution 2 - Google ChromeChad SciraView Answer on Stackoverflow