chrome扩展中的ContentScript.js没有监听background.js中的“message”

x0fgdtte  于 2023-05-27  发布在  Go
关注(0)|答案(1)|浏览(163)

我只是将此消息从background发送到contentScript,内容应该侦听此消息并执行函数。
我的contentScript.js:

function clickButton() {
  const sendButton = document.querySelector('span[data-testid="send"]');
  if (sendButton) {
    console.log("Button Clicked");
    sendButton.click();
    // Communicate back to the background script or popup
    chrome.runtime.sendMessage({ action: "buttonClicked" });
  }
}

// Execute the clickButton function when a message is received
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === "clickButton") {
    console.log("Content Script HIT") ;
    clickButton();
  }
});

background.js:

chrome.tabs.create({ url: url }, function (tab){
    
    chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
      if (tabId === tab.id && changeInfo.status === "complete") {

         console.log('TAB CREATED') ; 
       
         chrome.tabs.sendMessage(tab.id, { action: "clickButton" }, function (response) {
          console.log('Response from ContentScript', response);
          sendResponse({ success: true });
        });
        

        }
      });
    })

官方的chrome文档似乎也没有比我已经做的更有帮助
https://developer.chrome.com/docs/extensions/mv3/messaging/

z2acfund

z2acfund1#

让我来回答那些为同一个问题而挣扎的人:
问题是我的***manifest.json***,我缺少以下字段。表示您的***contentScript.js***应该在哪个主机/平台上执行:

"content_scripts": [
{
  "matches": ["https://anyurl.com"],
  "js": ["contentScript.js"]
}

]
此外,要在所有网页上执行contentScript,您可以用途:

"matches": ["<all_urls">]

相关问题