如何从background.js访问内部资源 [英] How to access internal resources from background.js
问题描述
在谷歌Chrome应用程序中,是否可以从 background.js
脚本中访问捆绑的数据文件?
In a Google Chrome application is it possible to access bundled data files from within the background.js
script?
EG如果我在应用程序中包含一个名为 data.json
的文件,那么我可以在 background.js中使用一个JavaScript API吗? / code>获取文件内容的脚本?
E.g. if I had a file called data.json
that I include with the app, is there a JavaScript API that I could use in the background.js
script to get at the files contents?
使用示例包目录结构:
/app/manfifest.json
/app/backround.js
/app/data.json
我想做类似的事情:
chrome.app.runtime.onLaunched.addListener(function() {
data = unknown.api.loadFileSync("data.json");
// do stuff with data
// ...
});
推荐答案
在API文档中,您可以获得 DirectoryEntry 对象为包目录,然后使用HTML5 FileSystem API获取文件的内容。 API函数是 chrome.runtime.getPackageDirectoryEntry 。
In the API docs you can get the DirectoryEntry object for the package directory, and then using the HTML5 FileSystem API get the contents of the file. The API function is chrome.runtime.getPackageDirectoryEntry.
chrome.runtime.getPackageDirectoryEntry(function (dirEntry) {
dirEntry.getFile("data.json", undefined, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader()
reader.addEventListener("load", function (event) {
// data now in reader.result
console.log(reader.result);
});
reader.readAsText(file);
});
}, function (e) {
console.log(e);
});
});
这篇关于如何从background.js访问内部资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!