I'm working on a chrome extension, trying to send data to API. While the server respond as expected, I find the chrome.runtime.onMessage method can't send response back to the corresponding chrome.runtime.sendMessage method. I've tried to wrap the codes in Promises, but somehow not working so far, please help me with it, thanx.
In brief, I send data from popup.html through popup.js to background.js, where the xmlhttprequest is made.
Here's the popup.js snipet:
/**
* Sending data to js/background.js
*/
const saveData = document.querySelector('#saveData')
saveData.addEventListener('click', async () => {
await chrome.runtime.sendMessage(
{
action: 'saveData',
params: { ...store }
},
(response) => {
console.log('response to saveData: ', response)
alert(response)
}
)
})
And the background.js:
chrome.runtime.onMessage.addListener(
async (request, sender, sendResponse) => {
if (request.action === 'saveData') {
// console.log(request.params)
await api_request(request.params)
.then(
data => {
console.log(data)
sendResponse(data)
}
)
}
}
)
// API Common params
const common_params = {
'app_type': 'biz',
'operator_id': 1
}
// Param set to be sent, will be composed later.
let params = {}
// Request API
const api_request = async (inputs) => {
const params = {
...common_params,
...inputs
}
const form_data = new FormData()
Object.keys(params).forEach(
(key) => {
form_data.append(key, params[key])
}
)
let message = ''
await new Promise((resolve, reject) => {
const request = new XMLHttpRequest()
request.open('post', 'https://api.somewhere.com/item/create', true)
request.onload = () => {
if (request.status === 200) {
const result = JSON.parse(request.response)
if (result.status === 200) {
message = result.content.message
}
else {
message = result.content.error.message
}
resolve(message)
}
else {
reject(Error(request.statusText))
}
}
request.onerror = () => {
reject(Error('Network Error'))
}
request.send(form_data)
})
return message // end Promise
}
popup.js console prints:
response to saveData: undefined
Unchecked runtime.lastError: The message port closed before a response was received.
background.js console.prints:
'Well Done on API'