Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Post a Comment for "Google Chrome Extension Http Request"