HTML5 File API in Firefox Addon SDK

吃可爱长大的小学妹 提交于 2019-12-13 14:21:02

问题


Is there a way to access Html5 file api in Fire Fox addon sdk in the content script?

This is needed in order to store user added words and their meanings. The data can grow large and so local storage isn't an option.

 window.requestFileSystem3 = window.requestFileSystem || window.webkitRequestFileSystem;

gives me the error TypeError: window.requestFileSystem3 is not a function.

I am asking this because i am porting this code from a Google Chrome Extension which allows accessing the file api in a content script.

Additional Questions

1) If HTML5 File API is not allowed then should i use file module?

2) Does the file module allow access to any file on the file system as opposed to the Html5 file api which only access to a sandboxed access to file system?

3) Assuming i have to use file module what would be the best location to store my files ( like the user profile directory or extension directory ) and how would i get this path in code.

I apologize for so many sub questions inside this questions. Google wasn't very helpful regarding this topic.

Any sample code would be very helpful.


回答1:


Firefox doesn't support writing files via File API yet and even when this will be added it will probably be accessible to web pages only and not extensions. In other words: yes, if you absolutely need to write to files then you should use low-level APIs. You want to store your data in the user profile directory (there is no extension directory, your extension is usually installed as a single packed file). Something like this should work to write a file:

var file = require("sdk/io/file");
var profilePath = require("sdk/system").pathFor("ProfD");
var filePath = file.join(profilePath, "foo.txt");
var writer = file.open(filePath, "w");
writer.writeAsync("foo!", function(error)
{
  if (error)
    console.log("Error: " + error);
  else
    console.log("Success!");
});

For reference: sdk/io/file, sdk/system

You could use TextReader.read() or file.read() to read the file. Unfortunately, Add-on SDK doesn't seem to support asynchronous file reading so the read will block the Firefox UI. The only alternative would be importing NetUtil and FileUtils via chrome authority, something like this:

var {components, Cu} = require("chrome");
var {NetUtil} = Cu.import("resource://gre/modules/NetUtil.jsm", null);
var {FileUtils} = Cu.import("resource://gre/modules/FileUtils.jsm", null);
NetUtil.asyncFetch(new FileUtils.File(filePath), function(stream, result)
{
  if (components.isSuccessCode(result))
  {
    var data = NetUtil.readInputStreamToString(stream, stream.available());
    console.log("Success: " + data);
  }
  else
    console.log("Error: " + result);
});


来源:https://stackoverflow.com/questions/12476871/html5-file-api-in-firefox-addon-sdk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!