在 Chrome 扩展名中逐行读取文本文件
Read a text file line by line in a Chrome Extension
我正在开发一个 Google Chrome 扩展,它将获取一个电子邮件地址并循环遍历白名单以查看我们是否获得匹配项。我正在使用 content.js
脚本中的函数,并且在与 manifest.json
相同的目录中有一个 whitelist.txt
文件。我正在尝试遍历 whitelist.txt
文件的每一行,但事实证明 JavaScript 相当困难。我能够读取文件并将其记录到控制台,但是当我尝试遍历每一行时,它将逐个字母地分解。我将如何逐行遍历文件?
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
...
返回的text
是一个字符串
您可以使用 split()
函数
逐字分隔
const words = text.split("\n"); //array of words
我正在开发一个 Google Chrome 扩展,它将获取一个电子邮件地址并循环遍历白名单以查看我们是否获得匹配项。我正在使用 content.js
脚本中的函数,并且在与 manifest.json
相同的目录中有一个 whitelist.txt
文件。我正在尝试遍历 whitelist.txt
文件的每一行,但事实证明 JavaScript 相当困难。我能够读取文件并将其记录到控制台,但是当我尝试遍历每一行时,它将逐个字母地分解。我将如何逐行遍历文件?
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
...
返回的text
是一个字符串
您可以使用 split()
函数
const words = text.split("\n"); //array of words