从扩展后台或弹出框到内容脚本的sendMessage不起作用 [英] sendMessage from extension background or popup to content script doesn't work

查看:130
本文介绍了从扩展后台或弹出框到内容脚本的sendMessage不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know that question has been repeatedly asked in different ways, but I tried to go through all the answers (hopefully I didn't miss anyone) and none of them worked for me.

这是我的扩展程序代码:

Here is my extension's code:

清单:

{
"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之一则不起作用.

The two alerts of the background page work, while the one of the content_script doesn't.

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

console log's message: Port error: Could not establish connection. Receiving end does not exist.

我的错在哪里?

推荐答案

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

In your background page you should call

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

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

instead of using chrome.extension.sendMessage as you currently do.

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

The chrome.tabs variant sends messages to content scripts, whereas the chrome.extension function sends messages to all other extension components.

这篇关于从扩展后台或弹出框到内容脚本的sendMessage不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆