I am looking for a function inside a webpage te activate a chrome extension.
Imagine that http://www.example.com/test.html contains:
<script>
hello();
</script>
And my background page contains the definition of the hello
function:
function hello() {
alert("test");
}
How can I make sure that the Chrome extension's background page's hello
is called when test.html
calls hello();
?
There is a builtin solution to Send messages from web pages to the extension
mainfest.json
Web page:
Extension's background script:
Before a web page is able to call a background page's function, the following problems need to be solved:
hello();
from a web page. This is done by injecting a script defininghello
using Content scripts. The injected function communicates with the content script using a custom event orpostMessage
.chrome.runtime.sendMessage
.If the web page needs to receive a reply as well:
sendMessage
/onMessage
, see below).postMessage
to send a message to the web page.All of these methods are asynchronous, and have to be implemented through callback functions.
These steps need to be designed carefully. Here's a generic implementation which implements all of the above steps. What you need to know about the implementation:
sendMessage
method whenever the content script need to be contacted.Usage:
sendMessage(<mixed message> [, <function callback>])
contentscript.js
background.js
A Chrome extension is not complete without a manifest file, so here's the
manifest.json
file which I used to test the answer:This extension was tested at http://jsfiddle.net/jRaPj/show/ (containing
hello();
as seen in the question), and shows a dialog saying "Background said: null".Open the background page, use
localStorage.setItem('whatever', 'Hello!');
to see that the message is correctly changed.No, with your above code because of background page(s) architecture
Yes with content scripts
Demonstration Using Content Scripts
manifest.json
Registering content scripts myscripts.js
Let me know if you need more information.