Skip to content

Instantly share code, notes, and snippets.

@yonran
Forked from anonymous/background.html
Created April 21, 2011 18:06
Show Gist options
  • Save yonran/935129 to your computer and use it in GitHub Desktop.
Save yonran/935129 to your computer and use it in GitHub Desktop.
Message Passing attempt
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({}); // snub them.
});
{
"name": "Test",
"version": "1.0",
// no more "background_page": "background.html",
"browser_action": {
"popup": "popup.html"
},
"permissions": [
"tabs", "http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["content_script.js"]
}
]
}
<script>
// Note that it's now popup.html instead of background.html. If you put
// it at the top of background.html, then it will run only ONCE, the first
// time the extension is loaded.
//
// You can put this call in the background if you really wanted, but it
// should be triggered by some event such as chrome.browserAction.onClicked.
// http://code.google.com/chrome/extensions/browserAction.html#event-onClicked
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
document.getElementById('response').textContent = response.farewell;
});
});
</script>
Hello, world!
<p>Response: <span id=response>Awaiting response...</span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment