我正在编写 chrome 扩展程序,并且正在尝试在背景页面和内容页面之间发送消息。
问题是连接从未建立。我什至从谷歌文档中复制了代码,但无济于事。
这是我的清单页面
{
  "name": "x",
  "description": "x",
  "version": "0.1",
  "permissions": ["contextMenus", "tabs", "notifications"],
   "content_scripts": [
    {
      "matches": ["http://*/*","https://*/*"],
      "js": ["jquery.js", "content_script.js"]
    }
  ],
  "background": {
    "scripts": ["sample.js"]
  },
  "manifest_version": 2
}
我的后台页面
function genericOnClick(info, tab) 
{
       //copy pasted from google tutorials. My own code also didn't work
       chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});
}
// Create a parent item and two children.
var parent1 = chrome.contextMenus.create({"title": "Rank Trigger", "contexts":["all"]});
var child1 = chrome.contextMenus.create
(
    {"title": "Rank 1", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
var child2 = chrome.contextMenus.create
(
    {"title": "Rank 2", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
var child2 = chrome.contextMenus.create
(
    {"title": "Rank 3", "contexts":["all"], "parentId": parent1, "onclick": genericOnClick}
);
内容脚本:
//copied from google tutorials
chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });
请问有什么想法吗?也许因为事件是从上下文菜单触发的,但我不太确定。我是 JS 和 chrome 扩展编程的新手。
谢谢