从background.js发送到contentScript.js

Sending from background.js to contentScript.js

本文关键字:js contentScript background      更新时间:2023-09-26

我做了文档中的操作,但在后台页面中说Cannot read property 'farewell' of undefined时出错。

我的背景.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
   console.log(response.farewell);
    console.log('ytr');
  });
});

发送该消息是因为我的console.log("测试")已打印出来。

我的contentScript.js看起来像这个

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

我确实在manifest.json中声明了权限选项卡和activeTab。我还错过了什么?

如果response未定义(这就是"无法读取未定义的属性…"的含义),则发送消息时出错。

在这种情况下,Chrome使用response == undefined调用回调并设置chrome.runtime.lastError

您需要检查错误值:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    if(chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError.message);
      return;
    }
    console.log(response.farewell);
    console.log('ytr');
  });
});

我敢打赌,你的内容脚本不知怎么没有被正确地注入。请参阅此答案以获取一些提示。