代码在控制台上运行良好,但在通过浏览器扩展注入时出错(适用于 chrome,不适用于 firefox)

Code runs fine on console but gives error when injected by browser extension(works on chrome not in firefox)

扩展注入以下代码:

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 但是当手动在控制台上运行时,它 works.Await 被用作

here is a video demo of the problem .

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

Top-level await enables developers to use the await keyword outside of async functions. It acts like a big async function causing other modules who import them to wait before they start evaluating their body.

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

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();

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