douxian0008 2016-01-09 21:06 采纳率: 0%
浏览 357
已采纳

消息从外部网页传递到chrome插件

I am trying to make a webpage send data to a chrome extension that will fire when user visit a website(say google here)

manifest.json

{
  "manifest_version": 2,
  "name": "Test Addon",
  "version": "0.01",
  "icons": { "16": "icon-16.ico" },

  "browser_action": {
  "default_icon" : "icon-16.ico",
  "default_popup" : "popup.html"
  },

   "content_scripts": [
    {
      "matches": ["*://*.google.com/*"  ],
      "js": ["cs.js"]
    }
  ],

  "externally_connectable": {
  "matches": ["*://*.mywebsite.com/*"]
}


}

cs.js

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    alert("world");
  });

mywebsite.com/testpage.php

// The ID of my chrome extension (In developer mode)
var editorExtensionId = "cjgeckgdpfhnedenpkaanpehddchlkle";

// Send a message
chrome.runtime.sendMessage("Hello");

</script>

As far as i know content script have access to onMessage and sendMessage but i don't get an alert when i visit google

  • 写回答

1条回答 默认 最新

  • douran6443 2016-01-10 08:08
    关注

    According to the docs, the extension id should be the first parameter when calling sendMessage(). You simply omitted this param.
    The second problem is that messages from external web page can receive only the background script. Check the docs for onMessageExternal().
    Use this code to send a message to your background extension script:

    // The ID of my chrome extension (In developer mode)
    var editorExtensionId = "cjgeckgdpfhnedenpkaanpehddchlkle";
    
    // Send a message
    chrome.runtime.sendMessage(editorExtensionId, "Hello");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))