如何从 chrome 扩展中的内容脚本获取另一个文件内容

How to get another file content from content script in chrome extension

我有一个 chrome 扩展名,其中包含这样的文件:

.
├── settings.json
├── manifest.json
└── ContentScript.js

像这样的清单

    "content_scripts": [
        {
            "js": [
                "ContentScript.js"
            ],
            "run_at": "document_end",
            "matches": ["https://example.com"]
        }
    ]

如何在 ContentScript.js 中从 settings.json 获取数据?

首先将此添加到清单中:

    "web_accessible_resources": [
        "settings.json"
    ]

强制文件可访问。

您可以在 url

上访问它
chrome.runtime.getURL("settings.json")

完整解决方案:

(async () => {
    var text = await fetch(chrome.runtime.getURL("settings.json")).then((responce) => {
        if (responce.ok) {
            return responce.text()// or responce.json() to json-style object
        } else { throw "Error: File was not found or can't be reached" }
    })
}).call()