JSONファイルをコンフィグとして読み込む

たとえば、次のようなJSONファイルがある:

{
  "google": "https://www.google.co.jp/",
  "yahoo": "http://www.yahoo.co.jp/",
  "": ""
}

これをコンフィグとして仮想配列に読み込みたい。

方法

Chrome 拡張のローカルファイルは、XMLHttpRequest により読み込むことができる。

ローカルファイルの URL 取得には、chrome.extension.getURL() を使う。

JSON のパースには JSON.parse を使う。

background.js

var config = {};

{
  var file = 'config.json';
  var xhr = new XMLHttpRequest();
  xhr.open('GET', chrome.extension.getURL(file), true);
  xhr.onreadystatechange = function() {
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
      config = JSON.parse(xhr.responseText);
    }
  };
  xhr.send();
}

{
  for (key in config) {
    if (typeof config[key] === 'string' && config[key] != '') {
      console.log('key=' + key + ', value=' + config[key]);
    }
  }
}

結果(background コンソール)

key=google, value=https://www.google.co.jp/
key=yahoo, value=http://www.yahoo.co.jp/

JSON のパース

もし eval を使おうとすると、こんなエラーになる:

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

Menifest.json にセキュリティーポリシーを追加すると、エラーを回避できる:

"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

しかし、当然、セキュリティリスクを抱えることになる。

そのため、前述のように、JSON のパースには JSON.parse を使うべき。