In a Google Chrome extension I want to pass messages between a content script and a popup page. I also want a function in the content script to be fired when a signal to do this is sent by the popup page to the content script.
The section in Google Chrome Extensions developer docs for messages, states that messages can be passed “from your content script to an extension page, or vice versa” (quoted from http://code.google.com/chrome/extensions/messaging.html )
Does this mean that I can send/receive messages between the content script and the popup page? Because the usage I have seen is for communication between background page and content script.
Or do I have to set up a 3 – way message passing route– viz.
content script <–> background page <–> popup page. And if this is the case, how do I set up messaging between background page <–> popup page?
And how do I fire a function in the content script, after sending signal to content script from the popup page? Does this also require background script to be present?
Content scripts can only send a message to the background page. If you want to send a message from a content script to a popup, you have to:
Send the message from the Content script to the background page.
Receive the message at the background.
Pass the message to the popup. To get a reference to the global
windowobject of the popup, usechrome.extension.getViews. Note: Unlike most of the other chrome APIs, this method is synchronous:In the popup, define the
whatevermethod.sendResponse(4) is called,details.sendResponse(see 3) is called. This, in turn, callsfunction() { /*response*/ }from 1.Note:
chrome.runtime.sendMessage/onMessageis only supported in Chrome 26+. Usechrome.extension.sendMessageif you want to support older browsers as well.