1

I'm making a Chrome Extension with MV3. I have a popup in which the user can select a language. The language needs to be read by an script which has to be injected into the website itself. However I can't read chrome.storage.sync neither can't i send a message in the injected script js file. So my question is how I would read data from chrome.storage inside a injected script file. I also tried setting a variable in a content script, but this also can't be read inside the injected script file.

manifest.json

{
    "manifest_version": 3,
    "permissions": ["storage"],
    "background": {
        "service_worker": "js/service_worker.js"
    },
    "content_scripts": [
        {
            "matches": ["*://.../*"],
            "js": ["js/content-script.js"]
        }
    ],
    "web_accessible_resources": [
        {
            "resources": ["js/inject.js"],
            "matches": ["*://.../*"]
        }
    ],
    "action": {
        "default_popup": "popup/popup.html"
    }
}

content-script.js

function importScript(src) {
    let s = document.createElement('script');
    s.src = chrome.runtime.getURL(src);
    s.onload = function() {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
}

window.hi = "test" // cant be read in the inject.js file...

importScript("js/inject.js")

inject.js

chrome.storage.sync.get() // undefined
window.hi // undefined

UPDATE I read through the docs again and stumbled upon window.postMessage which can be sent using content scripts and injected scripts! Question is closed.

  • It's better to use CustomEvent ([example](https://stackoverflow.com/a/19312198)) because many sites break if you send something they don't expect in postMessage. – wOxxOm Mar 31 '23 at 14:42
  • Oh thanks, I think then I'll rather use the custom event. – bananajoey88 Mar 31 '23 at 14:49

0 Answers0