我正在开发一个提取元数据的 chrome 扩展。解析元数据的代码包含在内容脚本中。background.js 和 content.js 通过 sendMessage 请求和响应进行通信。我遇到了 sendMessage 请求的异步性质的问题,我不确定如何解决它(即使在阅读了关于该问题的一连串讨论之后)。任何建议或方向将不胜感激。我怀疑我不知道如何将这些转换为回调。
背景.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});
内容.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)});
});