16

I'm trying to write a small add-on for firefox using the WebExtensions structure.

This add-on should read a local file content by it's absolute path:
"/home/saba/desktop/test.txt"

manifest.json

{

    "manifest_version": 2,
    "name": "Test - load files",
    "version": "0.0.1",

    "description": "Test - load files",
    "permissions": [ "<all_urls>" ],

    "background": {
        "scripts": [ "main.js" ]
    }

}


Here what I tried so far (inside the main.js):



Using XMLHttpRequest

function readFileAjax(_path){

    var xhr = new XMLHttpRequest();

    xhr.onloadend = function(event) {
        console.log("onloadend", this);
    };

    xhr.overrideMimeType("text/plain");
    xhr.open("GET", "file:///"+_path);
    xhr.send();
}

readFileAjax("/home/saba/desktop/test.txt");

Failed. I can't figure out why it always return an empty response
(test.txt contains "test", the path is correct)

onloadend XMLHttpRequest { 
    onreadystatechange: null, 
    readyState: 4, 
    timeout: 0, 
    withCredentials: false, 
    upload: XMLHttpRequestUpload, 
    responseURL: "", 
    status: 0, 
    statusText: "", 
    responseType: "", 
    response: "" 
}




Using FileReader

function readFileFR(_path){

    var reader  = new FileReader();

    reader.addEventListener("loadend", function() {
       console.log("loadend", this.result)
    });

    reader.readAsText(file);  // file ???? 
}

readFileFR("/home/saba/desktop/test.txt");

but here I got stuck because of the file argument.
This method usually get along with an input type="file" tag which gives back a .files array. (but I only have a local path string)

I searched if was possible to create a new Blob or File var using an absolute local file path but seams like it's not possible.




Using WebExtensions API

I didn't find any clue form the documentation pages on how to do this.

Isn't there (maybe) some kind of WebExtensions API which makes this possible like in the SDK?
https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/io_file
https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/io_text-streams




What am I doing wrong or missing?

..is it possible to get the content of a local file by it's absolute path with a WE Add-on?

Sabaz
  • 4,794
  • 2
  • 18
  • 26

2 Answers2

16

I finally found the way to do this using the Fetch requests and FileReader APIs.

Here what I came up to:

function readFile(_path, _cb){

    fetch(_path, {mode:'same-origin'})   // <-- important

    .then(function(_res) {
        return _res.blob();
    })

    .then(function(_blob) {
        var reader = new FileReader();

        reader.addEventListener("loadend", function() {
            _cb(this.result);
        });

        reader.readAsText(_blob); 
    });
};

Using the example in my question this is how to use it:

readFile('file:///home/saba/desktop/test.txt', function(_res){

    console.log(_res); // <--  result (file content)

});

ES6 with promises

If you prefer to use Promises rather than callbacks:

let readFile = (_path) => {
    return new Promise((resolve, reject) => {
        fetch(_path, {mode:'same-origin'})
            .then(function(_res) {
                return _res.blob();
            })
            .then(function(_blob) {
                var reader = new FileReader();

                reader.addEventListener("loadend", function() {
                    resolve(this.result);
                });

                reader.readAsText(_blob);
            })
            .catch(error => {
                reject(error);
            });
    });
};

Using it:

readFile('file:///home/saba/desktop/test.txt')
    .then(_res => {
        console.log(_res); // <--  result (file content)
    })
    .catch(_error => {
        console.log(_error );
    });
harvzor
  • 2,832
  • 1
  • 22
  • 40
Sabaz
  • 4,794
  • 2
  • 18
  • 26
  • 1
    This solution doesn't work anymore on Firefox 57, it gives me the error `TypeError: NetworkError when attempting to fetch resource`. Any insight? – beaver Jan 02 '18 at 11:14
  • @beaver are you using it in a WebExtensions project? I tried with a clean project on Firefox 58 and it seems to work. I published the test here [https://github.com/Lor-Saba/webextensions-readfile-from-path](https://github.com/Lor-Saba/webextensions-readfile-from-path) . I got your same error when trying to execute the code in the browser console – Sabaz Jan 03 '18 at 10:56
  • Thanks for your support. I've tried your test extension on Firefox 57 and 58 too, but I have the same error `TypeError: NetworkError when attempting to fetch resource`. Note that I'm on Windows. – beaver Jan 03 '18 at 11:20
  • @beaver oh, mmm.. I don't have a Windows istallation to test your case. I'll try to setup a virtual machine this weekend when I get home. – Sabaz Jan 03 '18 at 11:50
  • 2
    @beaver so, I played around a bit with that method on windows and, as my final response, I can say "yes it works... BUT". There's indeed something which is blocking Firefox to read files in some folders (maybe some kind of user R/W access control introduced in the newer versions of firefox?). For example, it was possible to read without problems from the root folder ( C:\ ) but not from the Desktop or Documents. I noticed something from the folders permissions (right click > properties > Security). Where it's possible to read the file there is "Everyone" listed in "Users & groups". – Sabaz Jan 06 '18 at 20:56
  • Tried with "Firefox 57.0.4" and "Firefox Dev 58.0b14" both 64bit – Sabaz Jan 06 '18 at 20:57
  • You are right, moving the file in C:\ I have no more that error. Thanks – beaver Jan 08 '18 at 14:15
  • 1
    Hello. I faced similar need. I will test this solution if it works for me. I wanted to ask: almost year has passed since the question asked and is still good to use this approach? Will it work in modern Firefox? – Tornike Shavishvili Jul 26 '19 at 11:07
0

This doesn't work, or at least not any longer taking the accepted answer into consideration.

Addon's run in a fake root meaning you can only ever access files which have been

  1. Shipped with your extension [1] using e.g. fetch() or
  2. Opened interactive (meaning initiated by the user using either the file picker or drag&drop) through the File() constructor [2]

Everything else will lead to a Security Error: Content at moz-extension://... may not load data from file:///... causing fetch() to throw the aforementioned TypeError: NetworkError when attempting to fetch resource.

[1] https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources
[2] https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_files#open_files_in_an_extension_using_a_file_picker

user1972814
  • 171
  • 2
  • 6