简体   繁体   English

Firefox WebExtensions,通过路径获取本地文件内容

[英]Firefox WebExtensions, get local files content by path

I'm trying to write a small add-on for firefox using the WebExtensions structure.我正在尝试使用WebExtensions结构为 firefox 编写一个小插件。

This add-on should read a local file content by it's absolute path:此附加组件应通过其绝对路径读取本地文件内容:
"/home/saba/desktop/test.txt" “/home/saba/desktop/test.txt”

manifest.json清单文件.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):这是我到目前为止尝试过的(在 main.js 中):



Using XMLHttpRequest使用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) (test.txt 包含“test”,路径正确)

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




Using FileReader使用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.但在这里我因为file参数而卡住了。
This method usually get along with an input type="file" tag which gives back a .files array.这种方法通常与一个input type="file"标签一起使用,它返回一个 .files 数组。 (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.我搜索了是否可以使用绝对本地文件路径创建新的BlobFile var,但接缝似乎不可能。




Using WebExtensions API使用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?是不是(也许)某种WebExtensions API使这成为可能,就像在 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_file
https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/io_text-streams 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? ..是否可以通过 WE Add-on 的绝对路径获取本地文件的内容?

I finally found the way to do this using the Fetch requests and FileReader APIs. 我终于找到了使用Fetch请求FileReader API执行此操作的方法。

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 ES6承诺

If you prefer to use Promises rather than callbacks: 如果您更喜欢使用Promises而不是回调:

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 );
    });

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插件运行在一个假的 root 中意味着你只能访问那些已经被

  1. Shipped with your extension [1] using eg fetch() or使用例如 fetch() 或
  2. Opened interactive (meaning initiated by the user using either the file picker or drag&drop) through the File() constructor [2]通过 File() 构造函数打开交互式(意思是由用户使用文件选择器或拖放启动)[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.其他一切都会导致Security Error: Content at moz-extension://... may not load data from file:///...导致 fetch() TypeError: NetworkError when attempting to fetch resource.抛出上述TypeError: NetworkError when attempting to fetch resource.

[1] https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources [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 [2] https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Working_with_files#open_files_in_an_extension_using_a_file_picker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM