douxian0008
2016-01-09 21:06
浏览 188

消息从外部网页传递到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

图片转代码服务由CSDN问答提供 功能建议

我正在尝试将网页发送到Chrome扩展程序,当用户访问网站时会触发(例如google) 这里)

manifest.json

  {
“manifest_version”:2,
“name  “:”测试插件“,
”版本“:”0.01“,
”图标“:{”16“:”icon-16.ico“},
 
”browser_action“:{
”default_icon  “:”icon-16.ico“,
”default_popup“:”popup.html“
},
 
”content_scripts“:[
 {
”匹配“:[”*:// *  .google.com / *“],
”js“:[”cs.js“] 
} 
 
,
 
”external_connectable“:{
”匹配“:[”*://  * .mywebsite.com / *“] \ N} 
 
 
} 
   
 
 

<强> cs.js

  chrome.runtime.onMessageExternal.addListener(
 function(request,sender,sendResponse){
 alert(“world”); 
}); 
  <  /pre>
nn

mywebsite.com/testpage.php

nn
//我的Chrome扩展程序的ID(在开发者模式下)  )
var editorExtensionId =“cjgeckgdpfhnedenpka  anpehddchlkle“; 
 
 //发送消息
chrome.runtime.sendMessage(”Hello“); 
 
&lt; / script&gt; 
   
 
 

As 据我所知,内容脚本可以访问onMessage和sendMessage但我在访问谷歌时没有收到警报

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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");
    
    已采纳该答案
    打赏 评论