Call the background of the Chrome extension from the site

I am looking for a function inside the te webpage that activates the chrome extension.

Imagine http://www.example.com/test.html contains:

<script> hello(); </script> 

And my man page contains a hello function definition:

 function hello() { alert("test"); } 

How can I make sure that the Chrome extension background page is called on the hello page when test.html calls hello(); ?

+7
javascript google-chrome google-chrome-extension content-script
Dec 08
source share
3 answers

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; // Simple example: Get data from extension local storage var result = localStorage.getItem('whatever'); // Reply result to content script sendResponse(result); } }); 

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.

+9
Dec 08
source share

No, with your previous code due to architecture background page (s)

Yes with content scripts

Content Scripting Demo

manifest.json

Registering myscripts.js content scripts

 { "name": "NFC", "description": "NFC Liken", "version": "0.1", "manifest_version": 2, "permissions": ["tabs", "http://*/", "https://*/"], "content_scripts": { "matches": "http://www.example.com/*", "js": [ "myscript.js"] }, "browser_action": { "default_icon": "sync-icon.png", "default_title": "I Like I Tag" } } 

Let me know if you need more information.

+1
Dec 08
source share

There is a built-in solution Send messages from web pages to the extension

mainfest.json

 "externally_connectable": { "matches": ["*://*.example.com/*"] } 

Webpage:

 // The ID of the extension we want to talk to. var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc"; // Make a simple request: chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url}, function(response) { if (!response.success) handleError(url); }); 

Background extension script:

 chrome.runtime.onMessageExternal.addListener( function(request, sender, sendResponse) { if (sender.url == blacklistedWebsite) return; // don't allow this web page access if (request.openUrlInEditor) openUrl(request.openUrlInEditor); }); 
0
Aug 19 '16 at 14:23
source share