sendMessage from background js to content js doesn't working but content js to background js works

43 Views Asked by At

content.js

chrome.runtime.onMessage.addListener(
    (request,sender,sendResponse) =>{
        console.log("Message is Received");
        console.log(request,sender,sendResponse);
        return true
    }
)
console.log("hello")

background.js

(async () => {
    const [tab] = await chrome.tabs.query({ url :"https://www.google.com/*"});
   console.log(tab)
    const response = await chrome.tabs.sendMessage(tab.id, {greeting: "hello"});
    // do something with response here, not outside the function
   
  })();

background.js:23 Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

error when running service worker.

when I tried to send message from content script to background js it works but not vice versa

I expect to receive message from background js to content js

1

There are 1 best solutions below

0
Abu On

content.js

 (
    async ()=>{
        chrome.runtime.onMessage.addListener(
          async (request,sender,sendResponse) =>{
                console.log("Message is Received");
                console.log(request,sender,sendResponse);
                return true
            }
        )
    }

)()

adding async in the listener and in callback function resolved my problem but I don't know how it resolved this anyone can explain