availablity check before run on active tab

This commit is contained in:
2020-01-11 20:40:25 +08:00
parent 341abebc66
commit f1cf32b83a
3 changed files with 20 additions and 6 deletions

View File

@ -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<string>} a promise of the report in message
* @returns {Promise<boolean>} 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;
}
/**

View File

@ -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) => {

View File

@ -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: