在我的扩展程序的内容脚本中,我从 background.js 请求数据,如下所示:
fireOnNewTopic (); // Initial run on cold start or full reload.
window.addEventListener ("hashchange", fireOnNewTopic, false);
function fireOnNewTopic () {
/*-- For the pages we want, location.hash will contain values
like: "#!newtopic/{group title}"
*/
if (location.hash) {
var locHashParts = location.hash.split ('/');
if (locHashParts.length > 1 && locHashParts[0] == '#!newtopic') {
var subjectStr = '';
var bodyStr = '';
switch (locHashParts[1]) {
case 'opencomments-site-discussions':
chrome.extension.sendMessage({name:"domain"},
function(response)
{
subjectStr = response.domain;
});
chrome.extension.sendMessage({name:"url"},
function(response)
{
bodyStr = "URL of last page visited: " + response.url;
});
break;
default:
break;
}
if (subjectStr && bodyStr) {
runPayloadCode (subjectStr, bodyStr);
}
}
}
}
不幸的是,由于 sendMessage() 与回调异步运行,在代码到达 runPayloadCode() 时,subjectStr 和 bodyStr 仍然为 null,因为 background.js 中的代码尚未完成。同步代码以便在调用 runPayloadCode() 时填充 subjectStr 和 bodyStr 的最佳方法是什么?