trouble-shooting
크롬 익스텐션 sendResponse 응답값 전달 안 되는 문제
fffman
2024. 12. 6. 23:12
content_script에서 chrome.runtime.sendMessage로 메시지를 보내면 background에서 chrome.runtime.onMessage.addListener로 받아서 sendResponse로 응답을 보내도록 했다.
간단히 코드를 구성하면 아래와 같다.
// content.js
chrome.runtime.sendMessage({
action: "test",
data: "Hello world",
}).then(response => {
console.log(response)
})
// background.js
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if(message.action === "test") {
console.log(message)
await asyncFunction() // 비동기 작업
sendResponse("ok")
}
}
그런데 content_script에서 response값이 undefined로 받아지는 것이다. 이유는 addListener에 async로 선언했기 때문이었다. 따라서 아래와 같이 수정해야 정상적으로 동작했다. 특히 return true를 통해서 메시지 채널을 유지해야한다고 한다.
// background.js
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if(message.action === "test") {
console.log(message)
asyncFunction().then(() => {
sendResponse("ok")
})
return true
}
}
아래 링크를 참고했다.
https://stackoverflow.com/questions/44056271/chrome-runtime-onmessage-response-with-async-await
chrome.runtime.onMessage response with async await
I want to use async await in an onMessage listener: chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{ var key = await getKey(); sendResponse(key); }); Howev...
stackoverflow.com