javascript 如何从chrome扩展程序读取文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28858027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:39:23  来源:igfitidea点击:

How to read file from chrome extension?

javascriptgoogle-chromegoogle-chrome-extension

提问by Tommz

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 codeattribute to insert content script code with string of retrieved HTML code.

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

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

我看到了一些使用XMLHttpRequestfrom content script 的方法,但是否可以避免这种情况?我尝试过chrome.fileSystem,但那是针对 chrome 应用程序而不是扩展程序。

回答by Xan

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.

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

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

您可以使用原始 XHR 来做到这一点,或者,如果您使用的是 jQuery,则使用$.ajax.

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

要从内容脚本执行此操作,您需要在"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 Filesystemaccess to your extension's files with chrome.runtime.getPackageDirectoryEntry:

您可以获得对扩展文件的只读HTML5 文件系统访问权限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.

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