background.js 如何在 Chrome 扩展程序的上下文中将 XHR 发送到服务器?

问题描述 投票:0回答:1

我想构建一个需要向 Node.js 服务器发送消息并接收响应的扩展。它应该自动执行此操作,这就是为什么我无法在 popup.js 中实现此操作。这是我的扩展端代码,用于向服务器发送消息:

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

这是我用于接收答案和回复的服务器端代码:

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

当我通过 popup.js 脚本运行此代码时,它可以工作。但是,当我通过 content.js 脚本运行此脚本时,它会被 CORS 策略阻止(“对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 ”)。我发现没有办法绕过CORS,因此认为最好通过background.js运行它。但随后我收到一个引用错误:“ReferenceError:XMLHttpRequest 未定义”。

我认为这是由于 XMLHttpRequest 未内置所致。应该有办法使用 npm 模块找到解决方法,但我经常读到这样做应该小心。这就是为什么我想问是否有概念上更简单的方法或者我是否理解不正确。谢谢!

javascript node.js google-chrome-extension xmlhttprequest client-server
1个回答
0
投票

Manifest V3 中要从后台自动发送请求,建议使用 chrome.alarms

background.js

await chrome.alarms.create("your_alarm_name", {periodInMinutes: 0.5})
chrome.alarms.onAlarm.addListener(alarmCallback)

// your request logic
function alarmCallback() {
    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)); 
    xhr.send()
}

就是这样!这是您在后台自动发送请求的方式。

但据我了解,您还需要一种在内容脚本中使用这些数据的方法。您可以使用 chrome.storage

来做到这一点

background.js

async function alarmCallback() {
    ...
    // Save your response to the extension's local storage
    await chrome.storage.local.set({xhrResponse: response})
}

然后您可以使用以下代码访问您的

xhrResponse

contentScript.js

// Content scripts have access to your extension's local storage too
const xhrResponse = await chrome.storage.local.get("xhrResponse")
© www.soinside.com 2019 - 2024. All rights reserved.