Chrome扩展程序:sendMessage从后台到内容脚本不起作用

Sub*_*way 76 background sendmessage google-chrome-extension content-script

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

这是我的扩展程序代码:

表现:

{
"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
}
Run Code Online (Sandbox Code Playgroud)

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"]});

});
Run Code Online (Sandbox Code Playgroud)

openDialog.js

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

  if (msg.action == 'open_dialog_box') {
    alert("Message recieved!");
  }
});
Run Code Online (Sandbox Code Playgroud)

后台页面的两个警报工作,而其中一个content_script没有.

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

我的错在哪里?

aps*_*ers 126

在您的背景页面中,您应该致电

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

而不是chrome.extension.sendMessage像你现在一样使用.

所述chrome.tabs变体将消息发送到内容的脚本,而chrome.extension功能将消息发送到所有其它的扩展部件.

  • 应该写什么来接收content-script.js? (11认同)
  • 谢谢.这是正确的,除了`chrome.tabs.sendMessage` [必须指定将它发送到哪个标签](http://developer.chrome.com/extensions/messaging.html).因此解决方案是更改为:`chrome.tabs.query({active:true},function(tabs){chrome.tabs.sendMessage(tab.id,{action:"open_dialog_box"},function(response){}) ;});` (6认同)
  • 这个解决方案对我不起作用。我完全遵循文档,我从 https://developer.chrome.com/extensions/messaging 复制了所有代码,这是非常简单的示例,但无法正确执行。出现错误无法建立连接。接收端不存在。有任何想法吗 (6认同)
  • @KushalJain我刚刚弄清楚了。在您的内容脚本JS文件中,您需要添加一个事件侦听器,例如:chrome.runtime.onMessage.addListener((message,sender,sendResponse)=&gt; {/ * Code Here * /});`message `是包含`{action:“ open_dialog_box”}`或您发送的任何内容的参数。“ sender”是一个包含您的Chrome扩展程序ID的对象。`sendResponse`是包含`function(response){}`的参数,或者是您处理消息后传递给您的任何函数的参数。 (4认同)

小智 16

@apsillers 是正确的。也不要忘记在您的内容脚本侦听器中返回 true 否则它可能会过早关闭。

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log(message)
    return true
});
Run Code Online (Sandbox Code Playgroud)

  • 我发誓,最简单的答案通常是正确的。我不敢相信这就是解决这个问题的方法,但它确实解决了。感谢分享! (2认同)

小智 7

所提供的解决方案的问题是它们会引发其他错误(这会破坏我的 Google Chrome)

@apsillers 解决方案有效,但回调会引发错误!

它应该是什么样子

// 背景.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"});  
});
Run Code Online (Sandbox Code Playgroud)

现在在 @Ronan Ca 提供的内容脚本中,该脚本基于 @apsillers 解决方案构建。由于我们从后台脚本中删除了回调,因此返回并不理想。

// 内容脚本.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(message)
// return true <- this and the callback in background.js are what caused a crash in extensions page of my Google chrome
});
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用回调来打开后台控制台,则后台控制台将不会打开。(这次车祸真是太糟糕了)