如何从 Chrome 扩展程序发送 HTTP GET 请求? [英] How do I send an HTTP GET request from a Chrome extension?
问题描述
我正在开发一个使用 GET 方法发送 HTTP 请求的 chrome 扩展.
I'm working on a chrome extension that sends a HTTP request using the method GET.
如何向 www.example.com
参数 par
发送一个值为 0
的 GET?
How do I send a GET to www.example.com
the parameter par
with value 0
?
https://www.example.com?par=0
(服务器读取参数par
并做某事)
(the server reads the parameter par
and does something)
我找到了这篇文章,讨论了 Cross-Origin XMLHttpRequest,但我没有知道他们的例子对我有什么帮助.
I found this article, talking about Cross-Origin XMLHttpRequest, but I don't know how their example could help me.
推荐答案
首先,您需要编辑您的 manifest.json
并为 www.example.com<添加权限/代码>:
First, you'll need to edit your manifest.json
and add the permission for www.example.com
:
对于新的 Manifest V3,请使用 <代码>host_permissions 字段:
{
"manifest_version": 3,
...
"host_permissions": [
"https://www.example.com/*"
],
...
}
如果您仍在使用旧的 Manifest V2,请使用 permissions
字段:
{
"manifest_version": 2,
...
"permissions": [
"https://www.example.com/*"
],
...
}
然后在你的后台页面(或其他地方)你可以这样做:
Then in your background page (or somewhere else) you can do:
fetch('http://www.example.com?par=0').then(r => r.text()).then(result => {
// Result now contains the response text, do what you want...
})
使用 XMLHttpRequest
(ES5) 的弃用版本:
Deprecated version using XMLHttpRequest
(ES5):
function callback() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
result = xhr.responseText;
// ...
}
}
};
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com?par=0", true);
xhr.onreadystatechange = callback;
xhr.send();
注意相关文档页面顶部的警告:
在 Manifest V3 中,后台页面不支持 XMLHttpRequest
(由 Service Workers 提供).请考虑使用它的现代替代品 fetch()
In Manifest V3,
XMLHttpRequest
is not supported in background pages (provided by Service Workers). Please consider using its modern replacement,fetch()
这篇关于如何从 Chrome 扩展程序发送 HTTP GET 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!