如何将来自Chrome扩展背景脚本的获取数据发送到内容脚本?

发布于 2025-01-22 16:08:55 字数 728 浏览 1 评论 0原文

在我的内容脚本中触发事件后,它将发送消息请求到背景脚本并等待响应。

content.js

chrome.runtime.sendMessage({ userId: userId }, function (response) {
    console.log(response);
});

background.js:

chrome.runtime.onMessage.addListener(function (
  request,
  sender,
  sendResponse
) {
  const userId = request.userId;
  if (userId) {
    fetchData(userId).then((data) => {
      sendResponse({ response: data });
    });
    return true;
  }
});

我已经尝试了异步/等待,将“返回true”移至if语句外部,但是在我的内容脚本中,响应要么是不确定的(即使fetchdata返回正确的数据),没有响应,也没有响应,或错误“消息端口在收到响应扩展之前关闭的消息端口”。

我想要的流程是:

  1. content.js将消息请求发送到background.js,并
  2. 背景
  3. 等待
  4. 响应 收到响应并记录数据

Once an event is triggered in my content script, it send a message request to the background script and waits for a response.

content.js

chrome.runtime.sendMessage({ userId: userId }, function (response) {
    console.log(response);
});

background.js:

chrome.runtime.onMessage.addListener(function (
  request,
  sender,
  sendResponse
) {
  const userId = request.userId;
  if (userId) {
    fetchData(userId).then((data) => {
      sendResponse({ response: data });
    });
    return true;
  }
});

I've tried async/await, moving the "return true" to outside the if statement, but in my content script the response is either undefined (even though fetchData returns the correct data), no response, or the error "the message port closed before a response was received extension".

The flow I want is:

  1. content.js sends a message request to background.js and waits for a response
  2. background.js receives the message
  3. background.js fetches data via http request
  4. background.js sends resolved promise back to content.js
  5. content.js receives response and logs the data

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜夜流光相皎洁 2025-01-29 16:08:55

事实证明,在收到响应之前,该问题正在更改弹出窗口中。在处理响应数据后,我通过移动命令将命令更改为响应中的弹出选项卡(window.open())来修复它。

The issue turned out to be changing tabs in the popup before the response was received. I fixed it by moving the command to change the popup tab (window.open()) to be in the response, after processing the response data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文