如何从Chrome扩展发送HTTP请求?

hl0ma9xz  于 2023-03-10  发布在  Go
关注(0)|答案(1)|浏览(456)

我正在开发一个发送HTTP请求的chrome扩展。
如何将其发送到www.example.com,参数par的值为0

https://www.example.com?par=0

(the服务器读取参数par并执行某些操作)
我找到了这篇文章,讨论Cross-Origin XMLHttpRequest,但我不知道他们的例子能对我有什么帮助。

im9ewurl

im9ewurl1#

首先,您需要编辑您的manifest.json并添加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/*"
    ],
    ...
}

然后,在您的背景页面(或其他地方),您可以:

fetch('http://www.example.com?par=0').then(r => r.text()).then(result => {
    // Result now contains the response text, do what you want...
})

另请参见MDN doc for fetch()
使用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();

注意相关documentation page顶部的警告:

在Manifest V3中,后台页面不支持XMLHttpRequest(由Service Workers提供)。请考虑使用其现代替代品fetch()

相关问题