如何将错误从扩展服务工作程序传递到内容脚本?

How to pass error from extension service worker to content script?

提问人:rnwst 提问时间:8/28/2023 最后编辑:rnwst 更新时间:8/28/2023 访问量:40

问:

我有一个浏览器扩展,其中我的内容脚本从后台脚本(Service Worker)请求信息。通常,这工作正常,但在某些情况下,后台脚本无法检索信息。在这种情况下,我希望后台脚本向内容脚本发送一个错误,其中包含有关问题性质的一些信息。

但是,当通过函数发送错误时,内容脚本仅接收一个空对象。为什么会发生这种情况,如何将错误从后台脚本发送到内容脚本?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(官方版本)

javascript chromium chrome-extension-manifest-v3 browser-extension

评论


答:

0赞 pppccc 8/28/2023 #1

空对象的来源可能是因为 chrome.runtime.sendMessage 要求消息是 JSON 可序列化的,但事实并非如此。new Error()

若要直接传递错误信息,需要执行如下操作:

const error = new Error('something bad happened');
const serializedError = JSON.stringify({
  message: error.message,
  name: error.name,
  stack: error.stack
});