I'm playing around with Promises available in Chrome extensions Manifest V3, but I'm not getting the expected results. What I'm trying to achieve: store some data from a browser action popup, then get a response back after the data is saved. Here's what I have so far:
background.js (service worker)
async function handleMessage(message, sender, sendResponse) {
switch (message.request) {
case 'setTimestamp':
await chrome.storage.local.set(message.data);
sendResponse({
status: chrome.runtime.lastError ? 'error' : 'ok'
});
break;
default:
sendResponse(null);
}
}
chrome.runtime.onMessage.addListener(handleMessage);
popup.js
// Event handler for button in popup.html
async function setTimestamp() {
const response = await chrome.runtime.sendMessage({
request: 'setTimestamp',
data: {
timestamp: performance.now()
}
});
console.log('setTimestamp response', response);
}
The timestamp is being saved successfully, but the response in popup.html is undefined
instead of {status: 'ok'}
that I was expecting. Can someone please point out what I'm doing wrong?
(Note: I'm aware you can use storage.local.set()
directly from the popup and validate that the data was saved successfully by detecting chrome.runtime.lastError
in the callback, but I wanted to use the new aync/await pattern above.)