Import a .json file to be used in content script


(Alexy Duhamel) #1

Hello there :slight_smile:

Since the switch from add-on to web extension i’m getting a bit lost, I can’t find a way to simply import a local .json file in my content script.
All I managed to do so far is to get the URL with `

var URL = browser.extension.getURL(“data/debrideurs.json”)

` but I just can’t find a way to use what is inside. This is probably a very simple thingto do, thank you for your time :slight_smile:


(Alexy Duhamel) #2

Nevermind, I’m probably too tired to code today x) It was only me, who forgot to write the subfolder where my jquery.js was… Time to go to sleep aha !


(Niklas Gollenstede) #3

There are at least three different approaches to this:

  1. Put your JSON object in the browser.storage.local from a background sscript and read it in the content script.
  2. Read any resource (including a JSON string) as a Blob in the beckground script and bessage it’s URL to the content:
/// in a background script with full access
const blob = await (await fetch(pathInPackage)).blob();
const tmpUri = URL.createObjectURL(blob);

/// in the restricted content script
const tmpUri = ; // get string from background via messaging
const json = await (await fetch(tmpUri)).json();
  1. Add the file to the web_accessible_resources. I’d always strictly avoid this, as it potentially allows every website to read the file as well.

(Alexy Duhamel) #4

Thank you :slight_smile: oh ok well i’m gonne change this


(Alexy Duhamel) #5

I have another question :slight_smile:
I used the local.storage method, wich work perfectly with json already in the code. But I would like to download it via a URL of this type "example.com/.../myfile.json"
I tried using in my background script :

var url = “example.com/.../myfile.json
$.getJSON(url, function (json) {
window.alert(json);
})

the jquery script is called before the background script.
I don’t get any message from this line, any idea why ? :slight_smile:
Thank you


(Niklas Gollenstede) #6

I don’t understand your problem.

I can tell you though that

  • you don’t need jQuery to fetch JSON. await (await fetch(url)).json() works just fine.
  • an URL should start with a scheme (e.g. https://).