Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable fetch POST in chrome extension contentScript?

I'm trying to call REST API in chrome extension. I managed to get fetch GET working , but couldn't make POST work. The body on server side is always empty. Here is my fetch request:

  let url = "http://localhost:3000/api/save/one"
  fetch(url, { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json; charset=utf-8" }, mode: "no-cors", body: JSON.stringify(json) })
  .then(resp => console.log(resp))

When I examined the request on server, I did notice that the content-type on server is always "text/plain;charset=UTF-8". So, my headers doesn't seem to be passed over. However, "Accept" header did go through.

This is the headers on server:

accept:"application/json"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"

If I remove "Accept" from my fetch headers, I got this on server:

accept:"*/*"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"

Any explanation on this? So, how to make POST work?

like image 688
newman Avatar asked Nov 21 '18 05:11

newman


People also ask

Can you use fetch for post request?

A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.

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.

How do I put background script extensions in Chrome?

The background script should be viewed as "running in the background of the Chrome browser". Your desired effect (running a script for every page) is actually a task for content scripts. To learn more, read https://developer.chrome.com/extensions/overview.html#arch.


1 Answers

You need to write the code for post method

Listener

background.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {    
    if (request.contentScriptQuery == "getdata") {
        var url = request.url;
        fetch(url)
            .then(response => response.text())
            .then(response => sendResponse(response))
            .catch()
        return true;
    }
    if (request.contentScriptQuery == "postData") {
        fetch(request.url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            },
            body: 'result=' + request.data
        })
            .then(response => response.json())
            .then(response => sendResponse(response))
            .catch(error => console.log('Error:', error));
        return true;
    }
});

Caller

Content_script.js

chrome.runtime.sendMessage(
    {
        contentScriptQuery: "postData"
        , data: JSONdata
        , url: ApiUrl
    }, function (response) {
        debugger;
        if (response != undefined && response != "") {
            callback(response);
        }
        else {
            debugger;
            callback(null);
        }
    });
like image 196
Rajput Vikash Rana Avatar answered Sep 19 '22 20:09

Rajput Vikash Rana