我正在研究提取元数据的chrome扩展程序。解析元数据的代码包含在内容脚本中。background.js和content.js通过sendMessage请求和响应进行通信。我遇到了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});
Run Code Online (Sandbox Code Playgroud)
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, …
Run Code Online (Sandbox Code Playgroud)