0

I have tried different ways to load a config.json file into a chrome extension, but none of them seems to work.

Tried using XHR: the response is empty E.g:

var xhr = new XMLHttpRequest;
xhr.open("GET", chrome.runtime.getURL("config.json"));
xhr.onreadystatechange = function() {
  if (this.readyState == 4) {
    console.log("request finished")
    console.log(xhr.responseText) // Returns empty
  }
};
xhr.send();

Tried using file and didn't work while granting the web_accessible_resources to that file in the manifest file.

const url = chrome.runtime.getURL('config.json');

fetch(url)
    .then((response) => {response.json()}) //assuming file contains json
    .then((json) => doSomething(json));  

Tried using this solution:

chrome.runtime.getPackageDirectoryEntry(function(root) {
        root.getFile("config.json", {}, function(fileEntry) {
            fileEntry.file(function(file) {
                var reader = new FileReader();
                reader.onloadend = function(e) {
                    var myFile = JSON.parse(this.result);
                    /*do here whatever with your JS object(s)*/
                };
                reader.readAsText(file);
            });
        });
    });

I get getPackageDirectoryEntry undefined

The only solution that works is obviously to include the json as an object into the javascript contentScript file but that is against code modularity.

Anyone with solution ?

Edit: This is my part of the manifest regarding the web_accessible_resources

"web_accessible_resources": [     
{       
"resources": [ "config.js"],       
"matches": [ "https://mywebsite/*" ]     
}
]
user3459435
  • 171
  • 1
  • 8
  • You didn't show your manifest.json so evidently there's a mistake in web_accessible_resources, for example you didn't specify the [correct URL pattern](https://stackoverflow.com/a/66638224) in `matches`. Note that `{response.json()}` won't return anything, it should be `response.json()` without {}. As for getPackageDirectoryEntry, it can't be used in content scripts. – wOxxOm Apr 25 '21 at 06:02
  • Use getPackageDirectoryEntry in the background.js file not in the content script. Regarding the manifest file, I used the following: ```javascript "web_accessible_resources": [ { "resources": [ "config.js", "test2.png" ], "matches": [ "https://mywebsite/*" ] }]``` – user3459435 Apr 25 '21 at 06:26
  • 1) Add `"manifest.json"` to `resources` to be able to access it in the content script and don't forget to reload the extension and the web page tab. 2) getPackageDirectoryEntry doesn't work in ManifestV3 service worker, it only works in extension pages like the popup/options and so on. – wOxxOm Apr 25 '21 at 06:39

0 Answers0