Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Chrome Extension Http request

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.

like image 498
Eugene Avatar asked Jan 19 '26 21:01

Eugene


1 Answers

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.
like image 112
sachleen Avatar answered Jan 22 '26 11:01

sachleen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!