Search code examples
javascriptbrowser-extension

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


The extension injects the following code:

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';
}

gives Uncaught SyntaxError: await is only valid in async function but when runned on console manually it works.Await is used as suggested here

here is a video demo of the problem .


Solution

  • You can run the code manually in the console because 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.

    To fix your code, you can simply wrap your code with an async function and run that function. Here is a possible implementation:

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

    More info about Top-level await.