在 chrome 扩展 content.js 中收到响应之前关闭。background.js 交互

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

我正在尝试从 content.js 到 background.js 进行通信,以将一些数据保存到 chrome.storage.local,但我不知道如何正确执行此操作。 我对 js 不太熟悉,所以如果这是一个愚蠢的问题,请原谅我。 这就是代码:

内容.js

function sendMessage(type) {
  chrome.runtime.sendMessage({ action: type }, (response) => {
    console.log(response);
  });
}

sendMessage("test");

背景.js

// Listen for messages from content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "test") {
    saveData(sendResponse);
  }
  return true;
});

// Function to save data to Chrome local storage
function saveData(sendResponse) {
  // Sample data to save
  const test = ["test1", "test2", "test3"];
  chrome.storage.local.set({ test: test }, () => {
  sendResponse("saved");
  });
}

结果:

undefined
Unchecked runtime.lastError: The message port closed before a response was received.

我做错了什么?

javascript asynchronous google-chrome-extension
1个回答
0
投票

尝试将返回值放在 if 语句中。响应应发送回发件人

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "test") {
    saveData(sendResponse);
    return true;
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.