简体   繁体   English

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

[英]How to read local file from webextension in Firefox?

As said in the subject, I need to fill a web form using data locally available as excel tables.正如主题中所说,我需要使用本地可用作 excel 表的数据填写 Web 表单。 I am already making that with a combination of python and autohotkey, but I want to have some level of JavaScript control in order to correctly handle loading times and conditionals.我已经使用 python 和 autohotkey 的组合来实现这一点,但我希望有一定程度的 JavaScript 控制,以便正确处理加载时间和条件。 As a web development newbie, I first thought I could just have a local iframe controlling the website where the form is, but I discovered soon enough that XSS thing that does not allow such a hack.作为一个 web 开发新手,我最初认为我可以只用一个本地 iframe 来控制表单所在的网站,但我很快发现 XSS 的东西不允许这样的黑客攻击。 I do not have access to the server.我无权访问服务器。

The last iteration of my experiences is with Firefox webextensions, with which I hoped to open a local file (through a html5 file input widget), where I would previously have written my js code to fill the form.我经验的最后一次迭代是使用 Firefox webextensions,我希望用它打开一个本地文件(通过 html5 文件输入小部件),我以前会在其中编写我的 js 代码来填充表单。 But apparently there are also limitations here, and I cannot make any sense out the docs I am looking at.但显然这里也有限制,我无法理解我正在查看的文档。 My code is currently like that:我的代码目前是这样的:

popup.html弹出窗口.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>

background-script.js背景脚本.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);

This works as a standalone file, but not as the popup.html file of my webextension.这可以作为独立文件使用,但不能作为我的 webextension 的 popup.html 文件使用。 In this case, none of the console.error lines are ever reached.在这种情况下,没有到达 console.error 行。 BTW, here is my manifest.json:顺便说一句,这是我的 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"
    }

}

Is there any easier way to do what I am doing?有没有更简单的方法来做我正在做的事情? I was expecting for this sort of thing to be a common need, am I wrong?我期待这种事情成为一种普遍需求,我错了吗? And why doesn't my code work?为什么我的代码不起作用?

This problem has been pointed out in this question: Firefox WebExtensions, get local files content by path .这个问题已经在这个问题中指出了: Firefox WebExtensions, get local files content by path The solution given there is the following:那里给出的解决方案如下:

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

but in this solution the absolute path has to be passed to the function, like here:但在这个解决方案中,绝对路径必须传递给函数,如下所示:

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

If you want to load a file from an <input> field you have to pass the path of the file too, because for security reasons you can't retrieve that from the <input> field.如果您想从<input>字段加载文件,您也必须传递文件的路径,因为出于安全原因,您无法从<input>字段中检索该文件。 My solution was to read the path from an input text field, reducing significantly the usability我的解决方案是从输入文本字段中读取路径,显着降低了可用性

html html

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

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

Note that unfortunately this solution doesn't work anymore on Firefox 57 , giving the error:请注意,不幸的是,此解决方案不再适用于 Firefox 57 ,并给出错误:

TypeError: NetworkError when attempting to fetch resource.

This works as a standalone file, but not as the popup.html file of my webextension.这可以作为独立文件使用,但不能作为我的 webextension 的 popup.html 文件使用。

Aha.啊哈。 I would check the permissions ...我会检查权限...

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

相关问题 如何从 Thunderbird WebExtension 执行/访问本地文件? - How to execute / access local file from Thunderbird WebExtension? Firefox WebExtension的XMLHttpRequest - XMLHttpRequest from Firefox WebExtension 如何在 Firefox WebExtension 的后台脚本中导入/使用外部 JavaScript 文件? - How to import/use an external JavaScript file in the background script of a Firefox WebExtension? 将WebExtension从Chrome移植到Firefox? - Porting WebExtension from Chrome to Firefox? 是否可以从Firefox扩展读取本地视频文件? - Is it possible to read local video file from Firefox extension? 如何在Firefox 45+版本的附件中读取本地文件 - How to read a local file in an add-on for Firefox version 45+ 如何在Firefox的WebExtension中覆盖XMLHttpRequest - How to override XMLHttpRequest in Firefox's WebExtension 如何使用页面 JavaScript 检查是否安装了 Firefox WebExtension? - How to check if a Firefox WebExtension is installed or not with page JavaScript? 如何使用Firefox从JavaScript读取本地文件 - How can I read local files from JavaScript with Firefox 通过Firefox附加组件(Webextension API)修改网页:如何正确访问元素? - Modifying a web page from Firefox add-on (Webextension API): how to access the elements properly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM