Loading an asset stored within a chrome extension

后端 未结 2 1295
执念已碎
执念已碎 2020-12-06 05:00

Let\'s say I have a JSON file stored within my extension called settings.json. I can get the URL of the file using:

chrome.extension.getURL(\"settings.json\         


        
相关标签:
2条回答
  • 2020-12-06 05:30

    If you make your setting.js look like:

    var settings =  {"param":value,...};
    

    Then you can just include it on a background page and use settings variable:

    <script src="settings.js"></script>
    

    If you want to have pure json in your file without assigning it to any variables then you can load it using XMLHttpRequest:

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = handleStateChange; // Implemented elsewhere.
    xhr.open("GET", chrome.extension.getURL('/config_resources/config.json'), true);
    xhr.send();
    

    or if you included jquery into your project:

    $.getJSON(chrome.extension.getURL('/config_resources/config.json'), function(settings) {
      //..
    });
    

    (btw using chrome.extension.getURL is required only if you are accessing a file from a content script, otherwise you can just use relative path /config_resources/config.json)

    0 讨论(0)
  • 2020-12-06 05:35

    I can verify that requesting the resource from an XHR in the background page works as previously described. Just be sure to add 'self' to the connect-src portion of your content_security_policy.

    0 讨论(0)
提交回复
热议问题