Chrome扩展程序无法成功将消息从后台发送到内容脚本

时间:2019-04-08 06:02:45

标签: google-chrome google-chrome-extension sendmessage content-script

我正在尝试创建一个扩展,该扩展在后台脚本中打开指定的URL,然后向在内容脚本侧打开的选项卡发送消息,但出现错误,但我没有确定我要去哪里错了。

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

background.js

let targetTab = "http://google.com"

main();

function main() {
  let active = true;
  let tabId = null;
  let tabUrl = null;
  if (active) {
    chrome.tabs.create({
      url: targetTab,
    }, (tab) => {
      console.log("Tab ID Generated: " + tab.id);
      tabId = tab.id;

      chrome.tabs.query({}, function (tabs) {
        tabs.forEach(tab => {
          console.log(tab.url);
          if (tab.url !== targetTab) {
            chrome.tabs.remove(tab.id);
          }
        })
        console.log("Tab ID Sent: " + tabId);
        chrome.tabs.sendMessage(tabId, {
          tabId,
          tabUrl, 
        }, (response) => {
          console.log(JSON.stringify(response));
        })
      })
    })
  }
}

content.js

chrome.runtime.onMessage.addListener(
    (request, sender, sendResponse) => {
        if (chrome.runtime.lastError) {
            console.log(chrome.runtime.lastError);
        }
        console.log("Got Message");
        sendResponse({message: "hi to you"});
    });

0 个答案:

没有答案
相关问题