代码在控制台上运行良好,但是在浏览器扩展注入时会给出错误(在Firefox中不支持chrome)

问题描述 投票:0回答:1

扩展名注入以下代码:

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用作suggested here

here is a video demo of the problem .

javascript browser-extension
1个回答
0
投票

您可以在控制台中手动运行代码,因为Chrome DevTools support "Top-level await"

顶级等待使开发人员可以在外部使用await关键字 异步功能。它像一个大的异步函数,导致其他 导入它们以等待评估开始之前的模块 身体。

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

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/));
}

async function main() {
  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();

有关Top-level await的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.