如何从Chrome扩展程序发送HTTP GET请求? [英] How do I send an HTTP GET request from a Chrome extension?

查看:373
本文介绍了如何从Chrome扩展程序发送HTTP GET请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个chrome扩展程序,该扩展程序使用GET方法发送HTTP请求.

I'm working on a chrome extension that sends an HTTP request using the method GET.

如何在www.example.com处发送值为0的参数par?

How do I send at www.example.com the parameter par with value 0?

www.example.com?par=0

(服务器读取参数par并执行一些操作)

(the server reads the parameter par and does some stuff)

我发现这篇文章是在谈论跨域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:

{
    "name": "My extension",
    ...
    "permissions": [
        "http://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):

Old (ES5) version using XMLHttpRequest:

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();


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

这篇关于如何从Chrome扩展程序发送HTTP GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆