Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

How do I send a GET to www.example.com with the parameter par with value 0?

https://www.example.com?par=0 

(the server reads the parameter par and does something)

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

like image 815
Firaja Avatar asked Aug 03 '14 18:08

Firaja


People also ask

How do I send an HTTP POST request from a Chrome extension?

Type the url in the main input field and choose the method to use: GET/POST/PUT/DELETE/PATCH. Click on the arrow "Send" or press Ctrl+Enter. You'll see info about the response (time, size, type) and you'll be able to see the content response in the response section.

Can Chrome extensions make requests?

When building a Chrome extension, you can make cross-site XMLHttpRequests via Content Scripts or the Background Page. Content Scripts is JavaScript that can get injected into a webpage and can manipulate the page's DOM.


1 Answers

First, you'll need to edit your manifest.json and add the permission for www.example.com:

  • For the new Manifest V3, use the host_permissions field:

    {     "manifest_version": 3,     ...     "host_permissions": [         "https://www.example.com/*"     ],     ... } 
  • If you are still using the old Manifest V2, use the permissions field:

    {     "manifest_version": 2,     ...     "permissions": [         "https://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... }) 

See also MDN doc for fetch().


Deprecated version using XMLHttpRequest (ES5):

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

NOTE the warning at the top of the relative documentation page:

In Manifest V3, XMLHttpRequest is not supported in background pages (provided by Service Workers). Please consider using its modern replacement, fetch()

like image 182
Marco Bonelli Avatar answered Oct 05 '22 02:10

Marco Bonelli