1

I'm tring to create Chrome Extension for private purposes. Already did some work, but stucked in the part where I have to read *.txt file into an array. Can you tell me please, what I supposed to do, to read content of *.txt file to an array. What exactly I have to write in manifest, and in main script? I really did researches, but my skills doesn't allow me to understand what I have to do.

I've trying the code below, but it gives an empty alert

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);        
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status === 0)
            {
                var allText = rawFile.responseText.split('\n');
                alert(allText);
            }
        }
    };
    rawFile.send(null);
}

readTextFile("file:///C:/Users/Admin/Desktop/PL/example.txt");
FasterBur
  • 11
  • 4
  • `"permissions": ["file:///*/"]` and make sure that file access is enabled on your extension's details page at chrome://extensions, then just use fetch/XHR to read the file URL as shown in many existing answers, split it into lines, etc. – wOxxOm Feb 26 '19 at 13:11
  • Your code looks fine assuming you're doing the request in an extension page (e.g. in a popup or a background script). Use devtools network panel to inspect the request. To invoke the correct devtools see [this info](https://stackoverflow.com/a/38920982). – wOxxOm Feb 26 '19 at 16:37
  • Inspector says: Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME file:///C:/Users/Admin/Desktop/PL/example.txt However when I put this link to address line fo browser it opens my txt-file – FasterBur Feb 27 '19 at 08:16
  • Works for me. Make sure your manifest has the permissions indicated in my first comment. – wOxxOm Feb 27 '19 at 08:19
  • Yes, it has. I did all your suggestions – FasterBur Feb 27 '19 at 08:36
  • Zip your extension and upload somewhere, then post a link here. – wOxxOm Feb 27 '19 at 09:14
  • This is ZIP with my extension https://transfiles.ru/01lqk – FasterBur Feb 27 '19 at 10:59
  • The code should be in an extension page e.g. in popup.js, not in a content script because content scripts are for web pages. You don't need a content script for this task. – wOxxOm Feb 27 '19 at 11:10
  • Thank you so much. Now it finnaly works! – FasterBur Feb 27 '19 at 11:59
  • One more question: Is it possible to open a txt file on my HDD, and write some information in there? My 'example.txt' file needs to be updating from time to time – FasterBur Feb 28 '19 at 11:41
  • Extensions can't do that directly. You can probably create a file in the HTML5 FileSystem and have a symbolic link to it on your desktop. – wOxxOm Feb 28 '19 at 11:42

0 Answers0