如何从Firefox中的webextension读取本地文件?

问题描述 投票:3回答:2

如在主题中所述,我需要使用本地可用作excel表的数据填充Web表单。我已经使用python和autohotkey的组合来制作它,但是我希望有一定程度的JavaScript控制以正确处理加载时间和条件。作为一个Web开发新手,我首先想到我可以让一个本地iframe控制表单所在的网站,但我很快发现XSS的东西不允许这样的黑客攻击。我无法访问服务器。

我的经验的最后一次迭代是使用Firefox webextensions,我希望打开一个本地文件(通过html5文件输入小部件),我之前已经编写了我的js代码来填充表单。但显然这里也有局限性,我无法理解我正在研究的文档。我的代码目前是这样的:

popup.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <input type="file" id="liquida-file" name="liquida">
    <br>
    <script src="background-script.js"></script>
  </body>
</html>

背景的script.js

function handleFiles() {
    var fileList = this.files; /* now you can work with the file list */
    var myFile = fileList[0]
    var reader = new FileReader();

    reader.onloadend = function(evt){
    if (evt.target.readyState == FileReader.DONE) { // DONE == 2
            var filedata = evt.target.result;
        console.error("Analyzing file data")
        console.error(filedata)
        var data = JSON.parse(filedata)
        console.error(data)
    }
    };
    reader.readAsText(myFile)
}
var inputElement = document.getElementById("liquida-file");
inputElement.addEventListener("change", handleFiles, false);

这可以作为一个独立的文件,但不能作为我的webextension的popup.html文件。在这种情况下,没有到达console.error行。顺便说一句,这是我的manifest.json:

的manifest.json

{

    "manifest_version": 2,
    "name": "My extension",
    "version": "1.0",

    "description": "Retrieve local data.",
    "homepage_url": "http://Nonefornow",
    "icons": {
        "48": "icons/beautiful-icon.png"
    },

    "permissions": [
        "activeTab"
    ],

    "browser_action": {
        "browser_style": true,
        "default_icon": "icons/icon.png",
        "default_title": "My Ext",
        "default_popup": "popup.html"
    }

}

有没有更简单的方法来做我正在做的事情?我期待这种事情成为共同的需要,我错了吗?为什么我的代码不起作用?

javascript html5 firefox firefox-webextensions
2个回答
1
投票

在这个问题中已经指出了这个问题:Firefox WebExtensions, get local files content by path。给出的solution如下:

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

但是在这个解决方案中,绝对路径必须传递给函数,就像这里:

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

如果要从<input>字段加载文件,则必须传递文件的路径,因为出于安全原因,您无法从<input>字段中检索该文件。我的解决方案是从输入文本字段读取路径,显着降低可用性

HTML

path: <input type="input" id="importFilePathInput" value="file://" />
<br />
file: <input type="file" id="importFileInput" />

JavaScript的

function importFromfile(){
  let filename = jQuery('#importFileInput').val().replace('C:\\fakepath\\', '');
  if (!filename) {
    console.log('Select a filename');
  } else {
    let path = jQuery('#importFilePathInput').val() + '/' + filename;
    if (!path.startsWith('file://')) {
      path = 'file://' + path;
    }
    fetch(path, {mode:'same-origin'})
      .then(function(result){
        return result.blob();
      })
      .then(function(blob){
        let reader = new FileReader();
        reader.addEventListener('loadend', function(){
          Model.save(JSON.parse(this.result)); // your function here
        });
        reader.readAsText(blob);
      });
  }
}

请注意,遗憾的是此解决方案在Firefox 57上不再起作用,给出错误:

TypeError: NetworkError when attempting to fetch resource.

-2
投票

这可以作为一个独立的文件,但不能作为我的webextension的popup.html文件。

啊哈。我会检查permissions ......

© www.soinside.com 2019 - 2024. All rights reserved.