I need to send two messages to my background script. The first one should get the title of the tab, the other one should send a message to store some data in local storage. This is what my code looks like right now:
// 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
}
}
}
});
My background script to get the title:
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;
}
The problem is that the pageTitle is always an empty string. How can I make the second sendMessage
wait for the first one? I think I need to use async/await. I tried promises, but the syntax was very confusing.