从后台js到内容js的sendMessage不起作用,但内容js到后台js可以工作

问题描述 投票:0回答:1

内容.js

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

背景.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.

运行 Service Worker 时出错。

当我尝试将消息从内容脚本发送到后台 js 时,它可以工作,但反之则不行

我期望收到从后台js到内容js的消息

javascript google-chrome-extension extension-methods
1个回答
0
投票

内容.js

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

)()

在侦听器和回调函数中添加异步解决了我的问题,但我不知道它是如何解决的,任何人都可以解释

© www.soinside.com 2019 - 2024. All rights reserved.