代码在控制台上运行良好,但在浏览器扩展注入时会出现错误(适用于 chrome 而不是在火狐中)



扩展注入以下代码:

var forbidden;
console.log("url: ",window.location.href);
async function fetchData(link) {
return fetch(link)
.then(response =>response.text())
.then(text => text.split(/r|n/))
}
forbidden=await fetchData(`https://truemysterious98.github.io/Page/uploads/txt/url/url.txt`);
for (var i =0;i<forbidden.length;i++){
console.log(forbidden[i]);
if(window.location.href.includes(forbidden[i])) window.location= 'https://truemysterious98.github.io/Page/t/m.html';
}

Uncaught SyntaxError: await is only valid in async function但是当在控制台上手动运行时,它可以工作。按照此处的建议使用 Await

这是问题的视频演示。

您可以在控制台中手动运行代码,因为 Chrome DevTools 支持"顶级等待"。

顶级 await 使开发人员能够在 异步函数。它就像一个大的异步函数,导致其他 导入它们的模块在开始评估其之前等待 身体。

要修复代码,只需使用异步函数包装代码并运行该函数即可。下面是一个可能的实现:

async function fetchData(link) {
return fetch(link)
.then((response) => response.text())
.then((text) => text.split(/r|n/));
}
async function main() {
console.log("url: ", window.location.href);
var forbidden = await fetchData(
`https://truemysterious98.github.io/Page/uploads/txt/url/url.txt`
);
for (var i = 0; i < forbidden.length; i++) {
console.log(forbidden[i]);
if (window.location.href.includes(forbidden[i]))
window.location = "https://truemysterious98.github.io/Page/t/m.html";
}
}
main();

有关顶级的更多信息等待。

最新更新