background - 从扩展后台或弹出窗口发送消息到内容脚本不起作用

标签 background google-chrome-extension sendmessage content-script

我知道这个问题已经以不同的方式被反复提出,但我尝试过一遍所有的答案(希望我没有错过任何人),但没有一个对我有用。

这是我的扩展程序的代码:

list :

{
"name": "test",
"version": "1.1",
"background": 
{ 
    "scripts": ["contextMenus.js"]
},

"permissions": ["tabs", "<all_urls>", "contextMenus"],

"content_scripts" : [
    {
        "matches" : [ "http://*/*" ],
        "js": ["jquery-1.8.3.js", "jquery-ui.js"],
        "css": [ "jquery-ui.css" ],
        "js": ["openDialog.js"]
    }
],

"manifest_version": 2
}

contextMenus.js

function onClickHandler(info, tab) {
    if (info.menuItemId == "line1"){

      alert("You have selected: " + info.selectionText);

      chrome.extension.sendMessage({action:'open_dialog_box'}, function(){});

      alert("Req sent?");

    }
}

chrome.contextMenus.onClicked.addListener(onClickHandler);

chrome.runtime.onInstalled.addListener(function() {

  chrome.contextMenus.create({"id": "line1", "type": "normal", "title": "I'm line 1",     "contexts":["selection"]});

});

openDialog.js

chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {

  if (msg.action == 'open_dialog_box') {
    alert("Message recieved!");
  }
});

后台页面的两个警报起作用,而 content_script 的一个则不起作用。

控制台日志消息:端口错误:无法建立连接。接收端不存在。

我的错在哪里?

最佳答案

在你的后台页面中你应该调用

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {});  
});

而不是像您目前那样使用chrome.extension.sendMessage

chrome.tabs 变体将消息发送到内容脚本,而 chrome.extension 函数将消息发送到所有其他扩展组件。

关于background - 从扩展后台或弹出窗口发送消息到内容脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14245334/

相关文章:

C# Skype4COM SendMessage 用户名

javascript - 将图像设置为背景

swift - 如何使背景图像适合 ScrollView ?

javascript - 如何从 Chrome devtools 扩展 "before"页面加载中公开函数?

c++ - SendMessage 收不到短信

javascript - Chrome 扩展发送消息

ios - 在iOS中设置全局背景图片或颜色

html - 如何使视频背景变暗?

javascript - Google Chrome 扩展中的 SOCKS5 代理身份验证

javascript - Chrome 扩展内容脚本之间的 postMessage 安全性如何?可能的替代方案?