
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函数,定义你的条件判断逻辑。 这两个方法都实现了依次请求和判断的目的,选择哪种方法取决于你的个人偏好。 方法一更简洁易读,方法二更接近递归的经典模式。
以上就是如何在tampermonkey中实现对多个链接的get请求并依次判断条件?的详细内容,更多请关注代码网其它相关文章!
发表评论