【问题标题】:"Could not establish connection. Receiving end does not exist" error trying to connect from React“无法建立连接。接收端不存在”错误尝试从 React 连接
【发布时间】:2020-04-24 18:50:32
【问题描述】:

Chrome 扩展程序在域 "http://localhost:3000" 的单独窗口中启动应用程序。该域使用应用程序 React。

我的反应应用:

反应:

componentDidMount() {
  let connectApp = chrome.runtime.connect(
    "ID My Chrome Extension",
      {
        name: "test",
      }
    );

    connectApp.onMessage.addListener((msg, sender, sendResponse) => {
      console.log(msg);
    });

    connectApp.onDisconnect.addListener((obj) => {
      console.log("disconnected port", obj);
    });
}

Chrome 扩展:

background.js


function sendInfoProspectWithDom(data) {
  chrome.runtime.sendMessage({
      text: "create-new-propsect"
  });
}

chrome.runtime.onConnect.addListener(function (obj) {
  console.log("onConnect");
});

ma​​nifest.json

{
  "manifest_version": 2,
  "name": "test",
  "version": "1.1.0",
  "description": "test Description",
  "browser_action": {},
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "content_scripts": [
    {
      "matches": ["*://mail.google.com/*"],
      "js": ["content.js"]
    }
  ],
  "externally_connectable": {
    "ids": ["*"],
    "matches": [
      "https://localhost:3000/*",
      "http://localhost:3000/*"
    ],
    "accepts_tls_channel_id": false
  },
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "permissions": [
    "tabs",
    "activeTab",
    "https://*/*",
    "http://*/*"
  ]
}

错误:

||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||||||||||||

【问题讨论】:

    标签: javascript reactjs google-chrome google-chrome-extension


    【解决方案1】:

    错误消息表示没有正确注册侦听器或在发送消息时未启用扩展。

    sending messages from web pages部分:

    在您的应用或扩展程序中,您可以通过运行时收听来自网页的消息。onMessageExternal 或运行时。onConnectExternal API,类似于跨扩展消息传递。只有网页可以发起连接。

    所以你需要将 onConnect 替换为 onConnectExternal:

    chrome.runtime.onConnectExternal.addListener(port => {
      //
    });
    

    【讨论】:

    • 谢谢。这个作品!!!我只能通过带有 background.js 的 port.postMessage 发送?我不能使用 chrome.runtime.sendMessage?
    • 要使用 sendMessage,您需要为 onMessageExternal 添加一个监听器,具体语法和参数请参见文档。
    猜你喜欢
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多