Firefox WebExtensions, get the contents of local files along the way

I am trying to write a small add-on for firefox using the WebExtensions framework .

This add-on should read the contents of the local file in the 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 is what I have tried so far (inside 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 understand why it always returns an empty answer
(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 am stuck due to file argument.
This method is usually combined with an input type="file" tag, which returns a .files array. (but I only have a local path string)

I searched if it was possible to create a new Blob or file var using the absolute path to the local file, but seams like this are impossible.




Using WebExtensions API

I did not find any help on the documentation pages on how to do this.

There is not (possibly) some kind of WebExtensions API that makes this possible, as 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 contents of a local file in an absolute path with a WE add-in?

+5
source share
1 answer

I finally found a way to do this using select queries and the FileReader API.

Here is what I went 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 an example in my question, here's how to use it:

 readFile('file:///home/saba/desktop/test.txt', function(_res){ console.log(_res); // <-- result (file content) }); 
+6
source

Source: https://habr.com/ru/post/1263958/


All Articles