Tampermonkey中依次處理多個(gè)GET請(qǐng)求并進(jìn)行條件判斷
在Tampermonkey腳本中,需要對(duì)多個(gè)鏈接發(fā)起GET請(qǐng)求,并根據(jù)返回結(jié)果依次進(jìn)行條件判斷,直到滿足條件或處理完所有鏈接。 直接使用GM_xmlhttpRequest并發(fā)請(qǐng)求并不能滿足“依次判斷”的需求,因?yàn)镚M_xmlhttpRequest本身并不支持取消請(qǐng)求。因此,我們需要采用串行請(qǐng)求的方式。
以下提供兩種實(shí)現(xiàn)方法:
方法一: 使用promise鏈?zhǔn)秸{(diào)用實(shí)現(xiàn)串行請(qǐng)求
這種方法利用Promise的then方法,實(shí)現(xiàn)請(qǐng)求的串行執(zhí)行和條件判斷。
async function processLinks(links, conditionFunc) { for (const link of links) { const response = await fetch(link); // 使用fetch代替GM_xmlhttpRequest,更現(xiàn)代化 const data = await response.text(); // 獲取響應(yīng)文本 if (conditionFunc(data)) { return data; // 滿足條件,返回結(jié)果并結(jié)束 } } return null; // 沒(méi)有鏈接滿足條件 } // 示例用法: const links = [ "https://example.com/link1", "https://example.com/link2", "https://example.com/link3" ]; const condition = (data) => data.includes("success"); // 判斷條件函數(shù) processLinks(links, condition) .then((result) => { if (result) { console.log("條件滿足,結(jié)果:", result); } else { console.log("所有鏈接均不滿足條件"); } }) .catch((error) => { console.error("請(qǐng)求錯(cuò)誤:", error); });
方法二: 使用遞歸函數(shù)實(shí)現(xiàn)串行請(qǐng)求
這種方法使用遞歸函數(shù),每次處理一個(gè)鏈接,并在滿足條件或處理完所有鏈接后結(jié)束遞歸。
function processLinksRecursive(links, conditionFunc, index = 0, result = null) { if (index >= links.length || result !== null) { return result; // 結(jié)束遞歸 } fetch(links[index]) .then(response => response.text()) .then(data => { if (conditionFunc(data)) { result = data; // 滿足條件 } else { result = processLinksRecursive(links, conditionFunc, index + 1, result); // 繼續(xù)遞歸 } }) .catch(error => console.error("請(qǐng)求錯(cuò)誤:", error)); return result; // 返回結(jié)果 } // 示例用法 (與方法一相同): const links = [ "https://example.com/link1", "https://example.com/link2", "https://example.com/link3" ]; const condition = (data) => data.includes("success"); const finalResult = processLinksRecursive(links, condition); if (finalResult) { console.log("條件滿足,結(jié)果:", finalResult); } else { console.log("所有鏈接均不滿足條件"); }
注意: 以上代碼使用了fetch API,它比GM_xmlhttpRequest更現(xiàn)代化,更容易使用。如果你的Tampermonkey環(huán)境不支持fetch,則需要替換回GM_xmlhttpRequest,并相應(yīng)調(diào)整代碼。 此外,記得根據(jù)你的實(shí)際情況修改conditionFunc函數(shù),定義你的條件判斷邏輯。 這兩個(gè)方法都實(shí)現(xiàn)了依次請(qǐng)求和判斷的目的,選擇哪種方法取決于你的個(gè)人偏好。 方法一更簡(jiǎn)潔易讀,方法二更接近遞歸的經(jīng)典模式。