我正在研究提取元数据的chrome扩展。解析元数据的代码包含在内容脚本中。 background.js和content.js通过sendMessage请求和响应进行通信。我遇到了一个与sendMessage请求的异步性质有关的问题,我不知道如何解决它(甚至在阅读了关于该问题的讨论之后)。任何意见或方向将不胜感激。我怀疑我没有得到如何将这些转化为回调。Chrome扩展:处理异步sendMessage。
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)});
});
的可能的复制[如何返回从异步调用的响应?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-电话) – wOxxOm