How do I send an HTTP GET request in chrome extens

2020-02-08 05:20发布

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

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

www.example.com?par=0

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

I found this article, talking about Cross-Origin XMLHttpRequest. But I don't know how their example could help me.

1条回答
混吃等死
2楼-- · 2020-02-08 05:48

You have to go to 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...
})

Old (deprecated) version using XMLHttpRequest:

var xhr = new XMLHttpRequest();

xhr.open("GET", "http://www.example.com?par=0", false);
xhr.send();

var result = xhr.responseText;

For more information on this topic, see the relative documentation page.

查看更多
登录 后发表回答