There are two types of message sending as explained in the Extensions Developer Guide – simple one-time requests and long-lived connections. This post will focus on simple one-time requests and sending a message from the content script to the background and sending a message back to the content script in response.
In this example, when the user presses Ctrl-Shift-Z a message will be sent from the content script to the background script. The background script receives the message, adds to the message and sends a message back to the content script.
Firstly, the manifest.json file for the extension specifies our background script and content script files to be used in the “content_scripts” and “background” sections respectively, as shown below:
{
"name": "Sending Messages Test",
"version": "1.0",
"description": "Send a Message to background.js from contentscript.js and send reply",
"permissions": ["tabs"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}
],
"background": { "scripts": ["background.js"] },
"manifest_version": 2
}
trigger_key = 90; //ASCII key code for the letter 'Z'
contentScriptMessage = "Skinner Said the teachers will crack any minute";
if (window == top) {
window.addEventListener('keyup', doKeyPress, false);
}
function doKeyPress(e){
if (e.shiftKey && e.ctrlKey && e.keyCode == trigger_key){
alert("Contentscript is sending a message to background script: '" + contentScriptMessage + "'");
chrome.extension.sendRequest({message: contentScriptMessage});
}
}
chrome.runtime.onMessage.addListener(
function(request, sender) {
alert("Contentscript has received a message from from background script: '" + request.message + "'");
});
var backgroundScriptMessage = " purple monkey dishwasher";
chrome.extension.onRequest.addListener(function(request, sender)
{
alert("Background script has received a message from contentscript:'" + request.message + "'");
returnMessage(request.message);
});
function returnMessage(messageToReturn)
{
chrome.tabs.getSelected(null, function(tab) {
var joinedMessage = messageToReturn + backgroundScriptMessage;
alert("Background script is sending a message to contentscript:'" + joinedMessage +"'");
chrome.tabs.sendMessage(tab.id, {message: joinedMessage});
});
}
The complete project which can be loaded as an unpacked extension into Chrome can be downloaded from here.



