【问题标题】:How to access internal resources from background.js如何从 background.js 访问内部资源
【发布时间】:2014-11-10 06:30:05
【问题描述】:

在 Google Chrome 应用程序中,是否可以从 background.js 脚本中访问捆绑的数据文件?

例如如果我有一个包含在应用程序中的名为 data.json 的文件,我是否可以在 background.js 脚本中使用 JavaScript API 来获取文件内容?

以示例包目录结构为例:

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

【问题讨论】:

    标签: javascript google-chrome-app


    【解决方案1】:

    后台脚本可以使用XHR 访问资源。要获取包含资源的 URL,请使用 chrome.extension.getURL(),它会返回资源的完全限定 URL。

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

    另一种方法是将data.json 文件转换为data.js 文件并将其作为后台脚本包含在manifest.json 中。这将允许您访问由data.js 设置的任何变量。

    ma​​nifest.json

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

    【讨论】:

    • 感谢您的回答,但是我找到了一种无需使用 ajax 请求的方法。我太早发布了我的问题!
    【解决方案2】:

    在 API 文档中,您可以获取包目录的 DirectoryEntry 对象,然后使用 HTML5 FileSystem API 获取文件的内容。 API函数为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);
        });
    });
    

    【讨论】:

    • 这个答案更适合我。由于我为我的应用程序使用清单版本 2,我无法使用 "web_accessible_resources"
    • @Harry 你错了。在清单 v2 之前,您可以在没有清单规范的情况下访问资源。对于 v2 及更高版本,您必须使用 web_accessible_resources 指定。
    【解决方案3】:

    由于firefox不支持getPackageDirectoryEntry,所以不推荐。现在有一个更简单的方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-06
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-27
      相关资源
      最近更新 更多