diff --git a/scripts/extract.js b/scripts/extract.js index bfe2900..46b568f 100644 --- a/scripts/extract.js +++ b/scripts/extract.js @@ -28,7 +28,7 @@ async function getData(itemsSelector, fieldSelectors, ...args) { if (arg instanceof Array) { urls = arg; } else if (arg instanceof ExractResult) { - urls = arg.squash().filter(v=>!!v); + urls = arg.squash().filter(v => !!v); } else { let urlTempl = arg; if (urlTempl) { @@ -103,7 +103,7 @@ function extractTabData(tab, itemsSelector, fieldSelectors) { itemsSelector: itemsSelector, fieldSelectors: fieldSelectors } - let cond = r => !!r; + let cond = r => r && r.length; return sendMessage(tab, req, cond); } @@ -139,31 +139,30 @@ function queryUrl(tab, urlExcluded) { * @param {object} tab the table where to send the message * @param {object} req the request data. * @param {function} cond success condition function, r:any=>boolean - * @param {number} failedTimeOut fail time out - * @param {number} detectInterval interval for detecting + * @param {number} interval interval for detecting * @return {Promise} a promise of the response. */ -function sendMessage(tab, req, cond, failedTimeOut, detectInterval) { +function sendMessage(tab, req, cond, interval) { req.from = "DataExtracter:" + req.from; - failedTimeOut = failedTimeOut || 10000; - detectInterval = detectInterval || 500; + interval = interval || 500; return new Promise((resolve, reject) => { - let timeOut; - let rejectTimeout = setTimeout(() => { - reject(`${req.from} failed after ${failedTimeOut/1000} seconds.`); - clearTimeout(timeOut); - }, failedTimeOut); + loop(); - function loop() { + async function loop() { + console.log("request for", req.from); + let tabAvailable = await getTabByID(tab.id); + if (!tabAvailable) { + throw new Error("Task interupted due to the target tab is closed."); + } + chrome.tabs.sendMessage(tab.id, req, r => { if (!cond || cond(r)) { - clearTimeout(rejectTimeout); resolve(r); } else { - timeOut = setTimeout(() => { + setTimeout(() => { loop(); - }, detectInterval); + }, interval); } }); } @@ -179,4 +178,12 @@ async function getActiveTab(currentWindow) { resolve(tabs[0]); }) }) +} + +async function getTabByID(id) { + return new Promise((resolve, reject) => { + chrome.tabs.get(id, function (tab) { + resolve(tab); + }) + }) } \ No newline at end of file