Tampermonkey中依次处理多个GET请求并进行条件判断
在Tampermonkey脚本中,需要对多个链接发起GET请求,并根据返回结果依次进行条件判断,直到满足条件或处理完所有链接。 直接使用GM_xmlhttpRequest并发请求并不能满足“依次判断”的需求,因为GM_xmlhttpRequest本身并不支持取消请求。因此,我们需要采用串行请求的方式。
以下提供两种实现方法:
方法一: 使用promise链式调用实现串行请求
这种方法利用Promise的then方法,实现请求的串行执行和条件判断。
async function processLinks(links, conditionFunc) { for (const link of links) { const response = await fetch(link); // 使用fetch代替GM_xmlhttpRequest,更现代化 const data = await response.text(); // 获取响应文本 if (conditionFunc(data)) { return data; // 满足条件,返回结果并结束 } } return null; // 没有链接满足条件 } // 示例用法: const links = [ "https://example.com/link1", "https://example.com/link2", "https://example.com/link3" ]; const condition = (data) => data.includes("success"); // 判断条件函数 processLinks(links, condition) .then((result) => { if (result) { console.log("条件满足,结果:", result); } else { console.log("所有链接均不满足条件"); } }) .catch((error) => { console.error("请求错误:", error); });
方法二: 使用递归函数实现串行请求
这种方法使用递归函数,每次处理一个链接,并在满足条件或处理完所有链接后结束递归。
function processLinksRecursive(links, conditionFunc, index = 0, result = null) { if (index >= links.length || result !== null) { return result; // 结束递归 } fetch(links[index]) .then(response => response.text()) .then(data => { if (conditionFunc(data)) { result = data; // 满足条件 } else { result = processLinksRecursive(links, conditionFunc, index + 1, result); // 继续递归 } }) .catch(error => console.error("请求错误:", error)); return result; // 返回结果 } // 示例用法 (与方法一相同): 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("条件满足,结果:", finalResult); } else { console.log("所有链接均不满足条件"); }
注意: 以上代码使用了fetch API,它比GM_xmlhttpRequest更现代化,更容易使用。如果你的Tampermonkey环境不支持fetch,则需要替换回GM_xmlhttpRequest,并相应调整代码。 此外,记得根据你的实际情况修改conditionFunc函数,定义你的条件判断逻辑。 这两个方法都实现了依次请求和判断的目的,选择哪种方法取决于你的个人偏好。 方法一更简洁易读,方法二更接近递归的经典模式。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END