Chrome extension: sendMessage from background to content script not working

I know that this question was repeatedly asked differently, but I tried to go through all the answers (I hope I didn’t miss anyone) and none of them worked for me.

Here is my extension code:

manifest:

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

Two background page warnings work, while one of the content_script is not working.

console log message: Port error: connection failed. End of reception does not exist.

Where is my fault

+43
google-chrome-extension background content-script sendmessage
Jan 09 '13 at 19:53
source share
1 answer

On your man 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 do now.

The chrome.tabs variant sends messages in the content script, while the chrome.extension function sends messages to all other extension components.

+84
Jan 09 '13 at
source share



All Articles