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
'trouble-shooting' 카테고리의 다른 글
데이터 관리 인터페이스 회고 (0) | 2024.12.29 |
---|---|
vue app 외부에서 메소드 호출하기 (3) | 2024.12.21 |
크롬익스텐션 content_script의 world속성 (0) | 2024.12.05 |
Firestore를 Python에서 사용할때 주의할점 (0) | 2024.12.04 |
오픈소스 PR 날리기 vite-plugin-chrome-extension 오류해결 (2) | 2024.11.30 |