How to access internal resources from background.js

百般思念 提交于 2019-12-17 16:59:11

问题


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

回答1:


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"]
}



回答2:


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



回答3:


Since getPackageDirectoryEntry is not supported by firefox, it is not recommended. Now there is a simpler way.

async function loadData(resourcePath) {
    var url = chrome.extension.getURL(resourcePath);
    return (await fetch(url)).text();
}


来源:https://stackoverflow.com/questions/26838004/how-to-access-internal-resources-from-background-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!