How to access internal resources from background.js
In google chrome app is it possible to access linked data files from background.js
script?
eg. if I have a file named data.json
that I include in my application, is there a JavaScript API I could use in a background.js
script to get the contents of the files?
Using the example directory structure:
/app/manfifest.json /app/backround.js /app/data.json
I want to do something like:
chrome.app.runtime.onLaunched.addListener(function() {
data = unknown.api.loadFileSync("data.json");
// do stuff with data
// ...
});
source to share
In the API docs, you can get a DirectoryEntry object for the package directory and then use the HTML5 FileSystem API to get the contents of the file. Chrome.runtime.getPackageDirectoryEntry API function .
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);
});
});
source to share
Background scripts can access resources using XHR
. To get the URL of an included resource, use chrome.extension.getURL()
that returns the full URL of the resource.
function loadData (file, fn) {
var dataUrl = chrome.extension.getURL(file),
xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onload = function () {
fn(null, this.response);
};
xhr.onerror = function () { fn(this.status); };
xhr.send();
}
chrome.app.runtime.onLaunched.addListener(function() {
loadData('data.json', function (err, data) {
//
});
});
Another approach is to convert the file data.json
to a file data.js
and include it as a script background in manifest.json
. This will allow you to access any variables set with data.js
.
manifest.json
"background": {
"scripts": ["data.js", "background.js"]
}
source to share