Reputation: 23
I want to open 100 links one by one and wait till each one is opened so that i can download data from it. How to wait till URL is opened in the tab?
function downloadreport()
{
chrome.tabs.getSelected(null,function(tab)
{
var reportlink=tab.url;
looplink=tab.url.slice(0,tab.url.length-1);
var indexcode=reportlink.indexOf('code')
reportlink=reportlink.slice(0,indexcode+4)+"/getReport.php";
var i;
for (i=0;i<100;i++)
{
chrome.tabs.update(tab.id,{url: looplink+i});
/*
How To Wait Here Till Tab Is Opened
*/
chrome.tabs.update(tab.id,{url: reportlink});
}
});
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('start').addEventListener('click',downloadreport);
});
Upvotes: 2
Views: 2047
Reputation: 73536
Use async/await, WebExtension polyfill, Promise, and tabs.onUpdated listener:
async function downloadreport() {
const [tab] = await browser.tabs.query({active: true, currentWindow: true});
let reportLink = tab.url.slice(0, tab.url.indexOf('code') + 4) + '/getReport.php';
let loopLink = tab.url.slice(0, -1);
for (let i = 0; i < 100; i++) {
await goToUrl(tab, loopLink + i);
await goToUrl(tab, reportLink);
}
}
function goToUrl(tab, url) {
browser.tabs.update(tab.id, {url});
return new Promise(resolve => {
browser.tabs.onUpdated.addListener(function onUpdated(tabId, info) {
if (tabId === tab.id && info.status === 'complete') {
browser.tabs.onUpdated.removeListener(onUpdated);
resolve();
}
});
});
}
Upvotes: 7