Home > Mobile >  Read a text file line by line in a Chrome Extension
Read a text file line by line in a Chrome Extension

Time:04-09

I am working on a Google Chrome Extension that will take an email address and loop through a whitelist to see if we get a match. I am working with functions inside a content.js script and I have a whitelist.txt file within the same directory as the manifest.json. I am attempting to iterate through each line of the whitelist.txt file but it is proving rather difficult with JavaScript. I am able to read the file and can log it to the console however when I attempt to iterate through each line it will break it up letter by letter. How would I go about iterating through the file line by line?

content.js 
  const url = chrome.runtime.getURL('whitelist.txt');

  fetch(url).then(function(response) {
      return response.text().then(function(text) {
        for (let i = 1; i < text.length; i  ) {
          /* Logic for seeing if email is on list */
          console.log(text[i]); /* Outputs the file line by line letter by letter. */
          return (email.test(text[i]));
        }
        //console.log(text); /* Outputs the entire txt file to the console */
      });
    });

whitelist.txt

...
yahoo.com
yahoo.com.ar
yahoo.com.au
yahoo.com.br
yahoo.com.cn
yahoo.com.hk
yahoo.com.is
yahoo.com.mx
yahoo.com.ph
yahoo.com.ru
yahoo.com.sg
yahoo.de
yahoo.dk
yahoo.es
yahoo.fr
yahoo.ie
yahoo.in
...

CodePudding user response:

The text being returned is a string You can separate it word by word with the split() function

const words = text.split("\n"); //array of words
  • Related