Search code examples
javascriptchrome-extension-manifest-v3

How can I fetch data in my content script? (chrome extension)


I'm trying to fetch a simple .json file from my we accessible ressources into my content script. Here is what I tried so far:

manifest.json

{
    "manifest_version": 3,
    "name": "MyExtension",
    "version": "0.0",
    "content_scripts": [{
        "matches": ["*://*/*"],
        "js": ["content.js"]
    }],
    "icons":{
            "128": "images/logo128x128.png"
    },
    "web_accessible_resources": [{
      "resources": ["data/data.json"],
      "matches": ["https://web-accessible-resources-1.glitch.me/*"]
    }]
}

content.js

const jsondict_url = chrome.runtime.getURL("data.json")
console.log(jsondict_url)

var jsondict = fetch(jsondict_url)

console.log(jsondict)

This is the error message I get:

chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/data.json
physique-generale-mecanique-PHYS-101-A#:1 
        
       Denying load of chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/data.json. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
       
content.js:6 Promise {<pending>}[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Failed to fetch
    at chrome-extension://hbjmkaohgphjcegliejkcehbmjeggnnb/content.js:4:16
content.js:4 
        
       GET chrome-extension://invalid/ net::ERR_FAILED
(anonymous) @ content.js:4
content.js:4 
        
      Uncaught (in promise) TypeError: Failed to fetch
    at content.js:4:16
(anonymous) @ content.js:4

Edit: my files are organized this way

images/ logo128x128.png

data/data.json

content.js

manifest.js


Solution

  • Correcting the path in 'content.js' to 'data/data.js' helped.

    I found one solution to my issue, I think I was misusing the function fetch. This introduction https://developers.google.com/web/updates/2015/03/introduction-to-fetch to it uses the following code:

    fetch('./api/some.json') // 'data/data.json' in my case
      .then(
        function(response) {
          if (response.status !== 200) {
            console.log('Looks like there was a problem. Status Code: ' +
              response.status);
            return;
          }
    
          // Examine the text in the response
          response.json().then(function(data) {
            console.log(data);
          });
        }
      )
      .catch(function(err) {
        console.log('Fetch Error :-S', err);
      });

    My extension works fine with this.