I'm working on a chrome extension that extracts meta data. The code which parses the metadata is contained in a content script. The background.js and content.js communicates via a sendMessage request and response. I'm running into an issue with the asynchronous nature of the sendMessage request and I'm not sure how to fix it (even after reading a litany of the discussions on the issue). Any advice or direction would be appreciated. I suspect I'm not getting how to turn these into callbacks.
background.js:
function onContextClick(info, tab) {
if( info["selectionText"] ){
var x = getMeta(tab);
//do stuff with x
}
}
function getMeta (tab) {
chrome.tabs.sendMessage(tab.id, {fetchTag: "meta,name,author,content"}, function(response) {
//alert(response.data);
//one thing I tired was to put my "do stuff" embedded here, but that didn't work either
return response.data;
});
}
var menu_id = chrome.contextMenus.create({"title": "Get Meta", "contexts":["selection"], "onclick": onContextClick});
content.js:
function fetchTag(string) {
var param = string.split(",");
return $(param[0] + "["+param[1]+ "=\"" + param[2] + "\"]").attr(param[3]);
}
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.fetchTag.length > 0)
sendResponse({data: fetchTag(request.fetchTag)});
});