繁体   English   中英

Chrome扩展程序的长期连接:从后台检索消息到内容

[英]Chrome extension long lived connection: retrieve message from background to content

我读了此书并在其他地方搜索过,但无法解决此问题。 我正在使用长期连接。 我将消息从内容脚本发送到后台,然后再将消息从背景脚本发送到内容脚本。 但是,由于某些原因,我无法在内容文件上接收消息...

内容脚本:

var port = chrome.runtime.connect({name: "my-channel"});

// receive messages
port.onMessage.addListener(function(msg) {
  console.log(msg); // doesn't log anything    
});

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('alertButton').addEventListener('click', function() { 
        // send message
        port.postMessage({myProperty: "value"});
    });
});

背景:

chrome.runtime.onConnect.addListener(function(port) {
    if(port.name == "my-channel"){
        port.onMessage.addListener(function(msg) {
           // do something
           // then send message to the content
           port.postMessage({myProperty: "value"});
        });
    }
});

编辑:我的manifest.json

{
  "manifest_version": 2,
  "name": "Test extension",
  "version": "1.0",
  "browser_action": {
  "default_popup": "main_ui.html",
  "default_title": "Test Extension"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["logic.js"]
  }],
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "permissions": [
    "tabs",
    "activeTab"
  ]
}

解决方案:我使用的是连接发生时的“端口”的旧引用。 侦听器的第二个参数(在那里不可见)实际上是端口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM