Chrome扩展:从的sendMessage背景内容脚本不起作用 [英] Chrome extension: sendMessage from background to content script doesn't work

查看:953
本文介绍了Chrome扩展:从的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.

下面是我的分机code:

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 为您目前。

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.

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

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