Last active
December 10, 2015 18:38
-
-
Save Lukewh/4476223 to your computer and use it in GitHub Desktop.
Message passing in Chrome extensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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