Send a message from content script
:
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
Send a message from an extension
to content script
:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
On the receiving end, you need to set up an runtime.onMessage event listener to handle the message. This looks the same from a content script or extension page.
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
APIs
- Fired when a message is sent from either an extension process or a content script.
-
Sends a single message to event listeners within your
extension
or a differentextension
.
If sending to your extension, theruntime.onMessage
event will be fired in each page.
Note thatextensions
cannot send messages tocontent scripts
using this method. To send messages tocontent scripts
, usetabs.sendMessage
.
chrome.runtime.onMessage.addListener(function callback)
chrome.runtime.sendMessage(string extensionId, any message, object options, function responseCallback)