3

I'd like to know if Google Chrome Extension can make a HTTP request and parse the body of the result (like Curl). For example, there is a server 1.2.3.4 that answers the question ?a=1&b=2 by summarizing the URL parameters. The query "http://1.2.3.4?a=1&b=2" would return a body containing 3, and my extension wants to submit such a query and parse the result.

Any help would be appreciated.

SetFreeByTruth
  • 819
  • 8
  • 23
Eugene
  • 220
  • 3
  • 9
  • Exact duplicate of http://stackoverflow.com/questions/10769924/how-can-chrome-extensions-basically-curl-other-pages, but the answers on that version are pretty sub-optimal -- one is a non-answer and the other is inappropriately written in jQuery. – apsillers Jul 16 '12 at 19:32

1 Answers1

14

Yes, using Cross-Origin XMLHttpRequest.

  1. Set the permissions in manifest.json

  2. Then use it like this in your extension page:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://api.example.com/data.json", true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        // WARNING! Might be injecting a malicious script!
        document.getElementById("resp").innerHTML = xhr.responseText;
        ...
      }
    }
    xhr.send();
    

Notes:

  • Content scripts can't make cross-origin requests in modern Chrome, more info.
  • ManifestV3 background script doesn't have XMLHttpRequest so you will use fetch there.
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
sachleen
  • 30,730
  • 8
  • 78
  • 73