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

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

问题描述

我有 popup.html,其中在通过单击浏览器操作加载弹出窗口时调用 popup.js.我正在以编程方式使用 chrome.tabs.executeScript() 注入内容脚本.我需要在页面正文中附加一个元素.如何在扩展名中插入来自不同 .html 文件的 HTML 代码,因为这样维护代码要容易得多.我想在 popup.js 中访问它(是否有一些 API 调用?)然后在 code 属性中插入带有检索到的 HTML 代码字符串的内容脚本代码.

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.

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

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.

推荐答案

正如评论中提到的,这只是向 chrome.runtime.getURL("myfile.html") 发出 GET 请求的问题,其中 "myfile.html" 是您想要的文件的相对路径(从扩展的根目录开始).

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.

您可以使用原始 XHR 来实现,或者,如果您使用的是 jQuery,则使用 $.ajax.

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

要从内容脚本执行此操作,您需要在 "web_accessible_resources" 中声明它.

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).

您可以获得对您的扩展程序的只读HTML5 文件系统访问权限带有 chrome.runtime.getPackageDirectoryEntry 的文件:>

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

如您所见,这比 XHR 请求复杂得多.只有在想要列出文件时才可能使用它.

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天全站免登陆