1

I have created a simple Chrome extension which stores all a few clicks on some Z webpage in my content_script. So, I want to know a way to send this data (json) to my node.js file (lets say /start).

How exactly to go about this? starting from sending data from the extension through ajax AND receiving this data in my /start router js file?

Any help appreciated. Thanks.

Abhijit S
  • 319
  • 2
  • 12

1 Answers1

4

I found a solution to my problem, if anyone falls into the same hurdle.

Basically, I sent the data from my content_script (js file) to background (js file) of my extension through chrome runtime message. Now Background file must be defined in the manifest, and is basically a file which runs in the background. From Here, I made a Web API call (XMLHttpRequest) from the background.js to my localhost server AND made it a POST function.

var xj = new XMLHttpRequest();
xj.open("POST", "http://localhost:3000/log", true);
xj.setRequestHeader("Content-Type", "application/json");
xj.send(JSON.stringify({ action: <your data>}));
xj.onreadystatechange = function () { if (xj.readyState == 4) { console.log(xj.responseText); } }

Now, in my node.js index page, I capture the send request in a Post function

router.post('/log', function(req, res, next){
     console.log(req.body) //Your data from the extension
});
Abhijit S
  • 319
  • 2
  • 12
  • does that intermediary exchange mandatory (passing the data from content_script to -> background) ? or can I right away make the request from content_script – emre-ozgun Nov 14 '21 at 09:26
  • @emre-ozgun I've tried calling my Express server directly from contentScript. The problem is that '/api/myservice' endpoints are resolved with the hostname of the webpage you are visiting with the browser, not 'localhost'. – altius_rup Mar 20 '23 at 15:40