I want to build an extension that requires sending a message to a node.js server and receiving a response. It should do this automatically, which is why I can’t implement this in popup.js. This is my extension-side code that sends a message to the server:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/data', true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const response = JSON.parse(xhr.responseText);
console.log(response.response);
}
};
const message = { message: 'Hello' };
xhr.send(JSON.stringify(message));
And this is my server-side code for receiving an answer and replying:
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/data') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const receivedMessage = JSON.parse(body).message;
console.log('Received message: ${receivedMessage}');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ response: 'Server received: ${receivedMessage}' }));
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
This code works when I run it through the popup.js script. When I run this through the content.js script though, it gets blocked by CORS policy (“Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”). I found out that there is no way to bypass CORS, and therefore think it is best to run it via background.js. But then I get a reference error: ‘ReferenceError: XMLHttpRequest is not defined’.
I assume that this is caused by XMLHttpRequest not being built-in. There should be ways to find workarounds using npm modules, but I often read that one should be careful doing so. This is why I want to ask if there is an conceptually easier way or if I did not understand something correctly. Thanks!
user25899957 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.