wait for elements

This commit is contained in:
2020-01-10 15:35:18 +08:00
parent 4656e4ff64
commit c504942144
5 changed files with 38 additions and 19 deletions

View File

@ -24,26 +24,30 @@
);
function extract(itemsSelector, fieldSelectors) {
// let fieldNotFound = false;
// since some elements may be loaded asynchronously.
// if one field is never found, we should return undefined,
// so that senders can detect to retry until elements loaded.
// If user writes wrong selectors, the task retries infinitely.
let fieldFound = {};
let items = Array.from(document.querySelectorAll(itemsSelector));
if (!items.length) return [];
// items may not loaded yet, tell the sender to retry.
if (!items.length) return MSG_ELEMENT_NOT_FOUND;
let results = items.map(
item => {
return fieldSelectors.map(
selector => {
let [cls, attr] = selector.split('@').slice(0, 2);
// TODO: close tab to cancel task tip
// if (fieldNotFound) return;
let fieldVals = Array.from(item.querySelectorAll(cls));
// if (!fieldVals.length) {
// fieldNotFound = true;
// return;
// }
if (!fieldVals.length) {
return;
}
fieldFound[selector] = true;
return fieldVals.map(find => attr ? find[attr] : find.textContent.trim()).join('\n')
}
)
}
);
// return fieldNotFound ? [] : results
return results;
// if it exists a field, which is not found in any row, the sender should retry.
let shouldWait = fieldSelectors.reduce((p, c) => p || !fieldFound[c], false);
return shouldWait ? MSG_ELEMENT_NOT_FOUND : results
}