如何在chrome扩展中发送HTTP GET请求?

Fir*_*aja 34 javascript google-chrome get xmlhttprequest google-chrome-extension

我正在使用chrome扩展,它使用GET方法发送HTTP请求.

如何使用值发送www.example.com参数?par0

www.example.com?par=0
Run Code Online (Sandbox Code Playgroud)

(服务器读取参数par并做一些事情)

我找到了这篇文章,谈论了Cross-Origin XMLHttpRequest.但我不知道他们的例子如何帮助我.

Mar*_*lli 63

你必须去你的manifest.json并添加以下权限www.example.com:

{
    "name": "My extension",
    ...
    "permissions": [
        "http://www.example.com/*"
    ],
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

有关此主题的更多信息,请参阅相关文档页面.

  • 我在尝试从我的内容脚本中调用 `fetch` 时遇到了 CORB 错误(将外部 URL 添加到 `permissions` 数组并不能解决问题)。以下答案解决了我的问题,即将 fetch 调用委托给后台脚本,并按照最初的预期在内容脚本中发送解析响应。/sf/ask/3865037991/#55215898 (4认同)
  • 就像一个注释:如果你在https页面上并且你正在请求一个http URL,你可能会得到一个"混合内容:页面''''错误. (2认同)
  • 是的,你可以使用*通配符.如果您想允许通过https和http进行访问,则必须单独添加.阅读https://developer.chrome.com/extensions/xhr (2认同)