diff --git a/scripts/background/actions.js b/scripts/background/actions.js index 485ff4e..18d6abb 100644 --- a/scripts/background/actions.js +++ b/scripts/background/actions.js @@ -110,16 +110,17 @@ function extractTabData(tab, itemsSelector, fieldSelectors) { } /** - * get report in from the target tab, usually used to detect if the content script is ready. + * ping target tab, usually used to detect if the content script is ready. * @param {any} tab target tab - * @returns {Promise} a promise of the report in message + * @returns {Promise} a promise of boolean value indicates if ping success */ -function reportIn(tab) { +async function ping(tab, count = 1) { let req = { action: ACTION_REPORT_IN } let cond = r => r == req.action; - return sendMessage(tab, req, 'Check tab availability...', cond); + let pong = await sendMessage(tab, req, 'Check tab availability...', cond, 1000, count).catch(() => { }); + return pong == ACTION_REPORT_IN; } /** diff --git a/scripts/background/extractor.js b/scripts/background/extractor.js index 1e2eeef..cc15e3d 100644 --- a/scripts/background/extractor.js +++ b/scripts/background/extractor.js @@ -56,6 +56,11 @@ class Extractor { tab = await createTab(task.urls[0], false); } else { tab = await getActiveTab(true) || await getActiveTab(false); + let succ = await ping(tab); + if (!succ) { + console.log('Cannot contact with active tab.'); + return; + } } this._running = true; return this._tasks.reduce((pms, task, i) => { diff --git a/scripts/background/messaging.js b/scripts/background/messaging.js index 78a04e3..92fdf9d 100644 --- a/scripts/background/messaging.js +++ b/scripts/background/messaging.js @@ -4,12 +4,15 @@ * @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} interval interval for detecting + * @param {number} interval retry interval, default: 500ms. + * @param {number} limit retry limit, default: 0, no limit. * @param {string} log messages logged to console. * @return {Promise} a promise of the response. */ -function sendMessage(tab, req, log, cond, interval) { +function sendMessage(tab, req, log, cond, interval, limit = 0) { interval = interval || 500; + limit = limit && !isNaN(limit) ? limit : 0; + count = 0; return new Promise((resolve, reject) => { loop(); @@ -22,6 +25,11 @@ function sendMessage(tab, req, log, cond, interval) { return; } + if (limit && count >= limit) { + reject(`sendMessage loop limit ${limit} reached.`); + return; + } + count++; chrome.tabs.sendMessage(tab.id, req, r => { // check error but do nothing. // do not interrupt promise chains even if error, or the task always fail when: