Abhijit S
Abhijit S

Reputation: 319

Send Data from chrome extension to Node.js

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.

Upvotes: 1

Views: 2423

Answers (1)

Abhijit S
Abhijit S

Reputation: 319

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

Upvotes: 4

Related Questions