我需要向我的后台脚本发送两条消息。第一个应该获取选项卡的标题,另一个应该发送消息以在本地存储中存储一些数据。这是我的代码现在的样子:
// value should be filled in here by the first received message (the title)
let pageTitle;
// get the tab title from the background script
chrome.runtime.sendMessage({ type: 'GET_TAB_INFO' }, (title) => {
pageTitle = title;
});
// include the retrieved tab title and store object in local storage
chrome.runtime.sendMessage({
type: 'CLICK_EVENT,
event: {
eventName: 'ELEMENT_SELECTED',
element: {
EventId: uuidv4('some-random-uuid'),
Metadata: {
PageTitle
}
}
}
});
我获取标题的后台脚本:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
const { type, ...rest } = request;
if (type === 'GET_TAB_INFO') {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
sendResponse(tabs[0].title);
});
}
return true;
}
问题在于 pageTitle 始终是一个空字符串。如何让第二个 sendMessage
等待第一个?我想我需要使用异步/等待。我尝试过 promise,但语法非常混乱。