Before a web page can call the background page function, the following issues must be resolved:
- Be able to use
hello(); from the web page. This is done by introducing a script that defines hello using content scripts. The function introduced is bound to the script content using a custom event or postMessage . - The content of the script should be bound to the background. This is implemented through
chrome.runtime.sendMessage .
If the webpage should also get a response: - Send a response from the man page (
sendMessage / onMessage , see below). - In the script content, create your own event or use
postMessage to send a message to a web page. - On the web page, process this message.
All of these methods are asynchronous and must be executed through callback functions.
These steps must be carefully designed. Here is a general implementation that implements all of the above steps. What you need to know about the implementation:
- In the code you
sendMessage use the sendMessage method whenever you need to contact the script content.
Usage: sendMessage(<mixed message> [, <function callback>])
contentscript.js
// Random unique name, to be used to minimize conflicts: var EVENT_FROM_PAGE = '__rw_chrome_ext_' + new Date().getTime(); var EVENT_REPLY = '__rw_chrome_ext_reply_' + new Date().getTime(); var s = document.createElement('script'); s.textContent = '(' + function(send_event_name, reply_event_name) { // NOTE: This function is serialized and runs in the page context // Begin of the page functionality window.hello = function(string) { sendMessage({ type: 'sayhello', data: string }, function(response) { alert('Background said: ' + response); }); }; // End of your logic, begin of messaging implementation: function sendMessage(message, callback) { var transporter = document.createElement('dummy'); // Handles reply: transporter.addEventListener(reply_event_name, function(event) { var result = this.getAttribute('result'); if (this.parentNode) this.parentNode.removeChild(this); // After having cleaned up, send callback if needed: if (typeof callback == 'function') { result = JSON.parse(result); callback(result); } }); // Functionality to notify content script var event = document.createEvent('Events'); event.initEvent(send_event_name, true, false); transporter.setAttribute('data', JSON.stringify(message)); (document.body||document.documentElement).appendChild(transporter); transporter.dispatchEvent(event); } } + ')(' + JSON.stringify(/*string*/EVENT_FROM_PAGE) + ', ' + JSON.stringify(/*string*/EVENT_REPLY) + ');'; document.documentElement.appendChild(s); s.parentNode.removeChild(s); // Handle messages from/to page: document.addEventListener(EVENT_FROM_PAGE, function(e) { var transporter = e.target; if (transporter) { var request = JSON.parse(transporter.getAttribute('data')); // Example of handling: Send message to background and await reply chrome.runtime.sendMessage({ type: 'page', request: request }, function(data) { // Received message from background, pass to page var event = document.createEvent('Events'); event.initEvent(EVENT_REPLY, false, false); transporter.setAttribute('result', JSON.stringify(data)); transporter.dispatchEvent(event); }); } });
background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { if (message && message.type == 'page') { var page_message = message.message;
The Chrome extension is not complete without a manifest file, so here is the manifest.json file that I used to verify the response:
{ "name": "Page to background and back again", "version": "1", "manifest_version": 2, "background": { "scripts": ["background.js"] }, "content_scripts": [{ "matches": ["http://jsfiddle.net/jRaPj/show/*"], "js": ["contentscript.js"], "all_frames": true, "run_at": "document_start" }] }
This extension has been tested at http://jsfiddle.net/jRaPj/show/ (containing hello(); as shown in the question), and shows the "Background" dialog saying: null ".
Open the source page, use localStorage.setItem('whatever', 'Hello!'); to see that the message has been correctly modified.