Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

javascript - How do I send an HTTP GET request from a Chrome extension?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...

})

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...