我有一个浏览器扩展,其中我的内容脚本从后台脚本(服务工作人员)请求信息。通常,这工作得很好,但在某些情况下,后台脚本无法检索信息。在这种情况下,我希望后台脚本向内容脚本发送一个错误,其中包含有关问题性质的一些信息。
但是,当通过
sendResponse
函数发送错误时,内容脚本仅收到一个空对象。为什么会发生这种情况以及如何将错误从后台脚本发送到内容脚本?
content-script.js
:
const showResult = (res) => {
console.log('Received the following response from background script:\n', res);
};
chrome.runtime.sendMessage('send me a user!').then((res) => showResult(res));
chrome.runtime.sendMessage('send me a user!').then((res) => showResult(res));
background-script.js
:
const responses = [
new Error('something bad happened'),
{ name: 'John Doe', age: 38 }
];
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const response = responses.pop()
console.log('Going to send the following response:\n', response);
sendResponse(response);
});
manifest.json
:
{
"manifest_version": 3,
"name": "A test",
"version": "0.0.1",
"content_scripts": [
{
"matches": ["https://www.google.com/*"],
"js": ["content-script.js"]
}
],
"background": {
"type": "module",
"service_worker": "background-script.js"
}
}
来自
background-script.js
的控制台输出:
Going to send the following response:
{name: 'John Doe', age: 38}
-------------------------------------------------------
Going to send the following response:
Error: something bad happened
at background-script.js:2:3
来自
content-script.js
的控制台输出:
Received the following response from background script:
{name: 'John Doe', age: 38}
-------------------------------------------------------
Received the following response from background script:
{}
浏览器:Chromium 版本 115.0.5790.170(官方版本)
空对象的来源很可能是因为
chrome.runtime.sendMessage
要求 message
可以 JSON 序列化,而 new Error()
则不然。
要直接传递错误信息,您需要执行以下操作:
const error = new Error('something bad happened');
const serializedError = JSON.stringify({
message: error.message,
name: error.name,
stack: error.stack
});