I have read tons of answers in stackoverflow but problem still exists.
Also went through the question chrome extension - sendResponse not waiting for async function
I implemented that but it doesn't work.
I have to use the async
function inside add event listener where I have to do API calls. If I will not use that and handle it with promise still I have to wait. How to wait for the response then?
in Background.js (service worker)
chrome.runtime.onMessage.addListener(async (object, sender, sendResponse) => {
if (object.id === 'checkUser') {
const { config: { url, token } } = object;
try {
const fetchResponse = await fetch(`https://${url}/api/check`, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
});
const result = await fetchResponse.json()
if (result.status) {
sendResponse({ status: true, message: 'Exist' })
return true
} else {
sendResponse({ status: false, message: 'Not exists' })
return true
}
} catch (error) {
console.log(error)
sendResponse({ status: false, message: 'Unable to check user', error: error })
}
// return true
} else {
sendResponse({ status: false })
return true
}
})
in popup.js
await chrome.storage.local.get(['url', 'token', 'user'], async (res) => {
const { token, url, user } = res
if (token && url) {
chrome.runtime.sendMessage({
id: 'checkUser',
config: {
token, url
}
}, (response) => {
console.log(response, 'inside Popup') \\ returns undefined
})
}
})
I have tried toggling return true
inside the onMessage.addListener. No error.,
Sometimes it shows
Unchecked runtime.lastError: The message port closed before a response was received.