Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

javascript - How to access internal resources from background.js

In a Google Chrome application is it possible to access bundled data files from within the background.js script?

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?

With the example bundle 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
  // ...
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Background scripts can access resources using XHR. To get the URL of the included resource, use chrome.extension.getURL(), which returns a fully-qualified URL for 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 data.json file into a data.js file and include it as a background script in manifest.json. This will let you access any variables set by data.js.

manifest.json:

"background": {
  "scripts": ["data.js", "background.js"]
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...