5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Chrome拡張でJSONファイルを手軽に読み込んでみよう!

Last updated at Posted at 2020-07-11

以下のような構造のChrome拡張のファイルがあったとします。

 my-extension
 ├── src
 │   ├── config.json
 │   └── main.js
 └── manifest.json

では、main.jsからconfig.jsonを読み込んでみましょう。なに、難しいことは考えず、以下の関数をコピペしてください。

#コード

main.js
function getJSON(filename) {
    return new Promise(function(r) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', chrome.extension.getURL(filename), true);
        xhr.onreadystatechange = function() {
            if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                r(xhr.responseText);
            }
        };
        xhr.send();
    });
}

getJSON('src/config.json').then(function(r) {
    //JSONファイルを読み込んだ後の処理
    var config = JSON.parse(r);
    console.log(config);
})

チャンチャン。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?