如何从chrome扩展中读取文件? [英] How to read file from chrome extension?

查看:992
本文介绍了如何从chrome扩展中读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有popup.html,其中popup.js是通过点击浏览器动作加载弹出框时调用的。在那里,我用 chrome.tabs.executeScript()以编程方式注入内容脚本。我需要将一个元素附加到页面的主体。如何在扩展名中插入来自不同.html文件的HTML代码,因为更容易维护这样的代码。我正在考虑在popup.js中访问它(是否有API调用?),然后在 code 属性内插入内容脚本代码和检索到的HTML代码字符串。

我在内容脚本中看到了一些使用 XMLHttpRequest 的方法,但是为了避免这种情况?我尝试使用 chrome.fileSystem ,但这是针对Chrome应用程序的,而不是扩展名。

解决方案

如上所述,这只是向 chrome.runtime.getURL(myfile.html)发出GET请求的问题,其中myfile.html是相对路径(从扩展名的根目录)到您想要的文件。



您可以使用原始XHR或者如果您使用jQuery,使用 $。ajax



做到这一点从内容脚本中,您需要在 web_accessible_resources中声明它




既然你不想那样,是的,还有另一种方式不适用于内容脚本)。



您可以获取只读 HTML5 Filesystem 访问你的扩展程序的文件使用 chrome.runtime.getPackageDirectoryEntry

  chrome.runtime.getPackageDirectoryEntry(function(root){
root.getFile(myfile .html,{},function(fileEntry){
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function(e){
//内容在this.result
};
reader.readAsText(file);
},errorHandler);
},errorHandler);
});

正如您所看到的,这比XHR请求复杂得多。如果想要列出文件,可能会使用它。


I have popup.html where popup.js is invoked when popup is loaded by clicking on browser action. There I'm programmatically injecting content scripts with chrome.tabs.executeScript(). I need to append one element to page's body. How can I insert HTML code from different .html file within extension, because it's much easier to maintain the code like that. I was thinking of accessing it within popup.js (is there some API call for that?) and then within code attribute to insert content script code with string of retrieved HTML code.

I saw some methods using XMLHttpRequest from content script, but is there to avoid that? I tried with chrome.fileSystem, but that's for chrome apps and not extensions.

解决方案

As a comment mentioned, it's just a question of making a GET request to chrome.runtime.getURL("myfile.html"), where "myfile.html" is the relative path (from the root of the extension) to the file that you want.

You can do that with raw XHR or, if you're using jQuery, using $.ajax.

To do it from a content script, you need to declare it in "web_accessible_resources".


Since you don't want that, yes, there is another way (not available to content scripts).

You can obtain a read-only HTML5 Filesystem access to your extension's files with chrome.runtime.getPackageDirectoryEntry:

chrome.runtime.getPackageDirectoryEntry(function(root) {
  root.getFile("myfile.html", {}, function(fileEntry) {
    fileEntry.file(function(file) {
      var reader = new FileReader();
      reader.onloadend = function(e) {
        // contents are in this.result
      };
      reader.readAsText(file);
    }, errorHandler);
  }, errorHandler);
});

As you can see, this is vastly more complicated than an XHR request. One would probably use this only if one wants to list the files.

这篇关于如何从chrome扩展中读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆