chrome extension OnMessage
My Demo extension is as follows
Files & Roles
a) manifest.json (Documentation)
b) myscript.js (Content Script See Documentation)
c) background.js (Background HTML File See Documentation)
d) popup.html (Browser Action Popup See Documentation)
e) popup.js (Receptor of Modified value from Background Page)
manifest.json
Registered all files to manifest(Viz background,popup,content scripts) with permissions
{"name":"Communication Demo","description":"This demonstrates modes of communication","manifest_version":2,"version":"1","permissions":["<all_urls>"],"background":{ "scripts":["background.js"]},"content_scripts": [ { "matches": ["<all_urls>"], "js": ["myscript.js"] } ],"browser_action":{ "default_icon":"screen.png", "default_popup":"popup.html"} }
myscript.js
Used sendMessage() API for communicating with background page
var d = document.domain;chrome.extension.sendMessage({ dom: d});
background.js
Added Event Listeners for Content and popup.js using onMessage() and onConnect() Listeners
var modifiedDom;chrome.extension.onMessage.addListener(function (request) { modifiedDom = request.dom + "Trivial Info Appending";});chrome.extension.onConnect.addListener(function (port) { port.onMessage.addListener(function (message) { if (message == "Request Modified Value") { port.postMessage(modifiedDom); } });});
popup.html
Sample browser action HTML Page registering popup.js to avoid Inline Scripting
<!doctype html><html> <head> <script src="popup.js"></script> </head> <body></body></html>
popup.js
Used Port\Long Lived Connection for communicating with background page for fetching results
var port = chrome.extension.connect({ name: "Sample Communication"});port.postMessage("Request Modified Value");port.onMessage.addListener(function (msg) { console.log("Modified Value recieved is " + msg);});
Hope this helps, let me know if you need more information