Chrome extension: sendMessage from background to content script doesn't work

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

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:

manifest:

{ "name": "test", "version": "1.1", "background":  {      "scripts": ["contextMenus.js"] },  "permissions": ["tabs", "", "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!");   } }); 

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.

Where is my fault?

回答1:

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) {});   }); 

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

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!