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

查看:23
本文介绍了从扩展后台或弹出到内容脚本的 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天全站免登陆