[英]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.我正在尝试从我们可访问的资源中获取一个简单的 .json 文件到我的内容脚本中。 Here is what I tried so far:
这是我到目前为止所尝试的:
manifest.json清单.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\/*"] }] }<\/code><\/pre>
content.js内容.js
const jsondict_url = chrome.runtime.getURL("data.json") console.log(jsondict_url) var jsondict = fetch(jsondict_url) console.log(jsondict)<\/code><\/pre>
![](/img/trans.png)
This is the error message I get:这是我收到的错误消息:
![](/img/trans.png)
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<\/code><\/pre>
![](/img/trans.png)
Edit: my files are organized this way编辑:我的文件是这样组织的
images\/ logo128x128.png图片\/ logo128x128.png
data\/data.json数据\/data.json
content.js内容.js
manifest.js manifest.js
"
Correcting the path in 'content.js' to 'data\/data.js' helped.将“content.js”中的路径更正为“data\/data.js”有帮助。
I found one solution to my issue, I think I was misusing the function fetch.我找到了一个解决我的问题的方法,我认为我滥用了函数 fetch。 This introduction https:\/\/developers.google.com\/web\/updates\/2015\/03\/introduction-to-fetch<\/a> to it uses the following code:
此介绍
https:\/\/developers.google.com\/web\/updates\/2015\/03\/introduction-to-fetch<\/a>使用以下代码:
My extension works fine with this.我的扩展程序适用于此。
"
You're trying getURL("data.json")<\/code> but your manifest states
"resources": ["data\/data.json"]<\/code> so the path is incorrect in atleast one place?
您正在尝试
getURL("data.json")<\/code>但您的清单声明
"resources": ["data\/data.json"]<\/code>所以路径至少在一个地方不正确?
It should be
getURL("data\/data.json")<\/code> .
它应该是
getURL("data\/data.json")<\/code> 。
You can also try adding
content.js<\/code> to
"web_accessible_resources"<\/code> .
您也可以尝试将
content.js<\/code>添加到
"web_accessible_resources"<\/code> 。
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.