Open tab, wait for it to finish loading then close it
chromium, google-chrome, google-chrome-extension, javascript
Solution
You can either bind a `chrome.tabs.onUpdated` or a `chrome.webNavigation.onCompleted` event to detect that a page has finished loading, or insert a content script to close the tab.
Using the `webNavigation.onCompleted` event
var tabsToClose = {};
chrome.webNavigation.onCompleted.addListener(function(details) {
if (details.frameId !== 0) return; // Only process top-frame requests
var tabId = details.tabId;
if (tabsToClose[tabId]) {
delete tabsToClose[tabId];
chrome.tabs.remove(tabId);
}
});
chrome.tabs.create({url: target, selected: false, pinned: true}, function(tab) {
tabsToClose[tab.id] = 1;
});
Note: I assumed that navigation will always succeed. You should also bind a `webNavigation.onErrorOccurred` event to close the tab on failure.
Using a content script
By using `runAt: 'document_idle'` (default), `window.close();` will be inserted once the page has finished loading.
chrome.tabs.create({url: target, selected: false, pinned: true}, function(tab) {
chrome.tabs.executeScript(tab.id, {
code: 'window.close();',
runAt: 'document_idle'
});
});
Problem
I have written my first chrome extension today. What I want it to do is open a tab in the background (pinned), and after the page in the tab finishes loading, I want the tab to close. So far I have: ``` chrome.tabs.create({url: target, selected: false, pinned: true}); ``` What the above code does is open the tab in the background, and pin it. How do I close the tab once it has finished loading?