Skip to content

Instantly share code, notes, and snippets.

@Lukewh
Last active December 10, 2015 18:38
Show Gist options
  • Save Lukewh/4476223 to your computer and use it in GitHub Desktop.
Save Lukewh/4476223 to your computer and use it in GitHub Desktop.
Message passing in Chrome extensions
chrome.extension.onMessage.addListener(
/*
request = payload
sender = information about the payload
sendResponse = function to send response to. Explanation above (1).
*/
function(request, sender, sendResponse){
var tabId = sender.tab.id, // Which tab is the query from?
isValid;
/*
Check the request is valid here
*/
if (!isValid) {
sendMessage(tabId, 'Error'); // Send an error to the right tab
return; // Stop execution
}
getXHR('[atlasUrl]' + request, function(error, results){
if (error) {
sendMessage(tabId, 'Error');
} else {
sendMessage(tabId, results);
}
});
}
);
function sendMessage(tab, data) {
if (tab && data) {
chrome.tabs.sendMessage(tab, data);
}
}
chrome.extension.onMessage.addListener(function(results) { // Listen for results
// Append results to the DOM
});
function sendMessage(data) {
if (data) {
chrome.extension.sendMessage(data, false); // false here can be replaced with
} // a function. Explanation below (1).
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment