繁体   English   中英

无法将消息从 popup.js 发送到 chrome 扩展中的 content.js

[英]Unable to send message from popup.js to content.js in chrome extension

我一直在构建扩展并尝试在单击弹出窗口中的按钮时向内容脚本发送消息,但一直收到此错误“无法建立连接。接收端不存在。” 有时还会在 popup.js 中出现“Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')”

// 清单.json 文件

{
  "manifest_version": 3,
  "name": "Extension",
  "version": "1.0",
  "action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "js": ["content.js"],
      "matches": ["https://discord.com/channels/*"]
    }
  ],
  "permissions": ["tabs"],
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["https://discord.com/channels/*"]
}

   
    

// popup.js 文件。

const sendMessageBtn = document.querySelector("button");

sendMessageBtn.addEventListener("click", async () => {
  console.log("clicked");       // being logged to console
  const [tab] = await chrome.tabs.query({
    active: true,
    lastFocusedWindow: true,
  });
  const response = await chrome.tabs.sendMessage(tab.id, { greeting: "hello" });
  // do something with response here, not outside the function
  console.log(response);
});

单击按钮时出现错误:“无法建立连接。接收端不存在。” 在扩展错误日志中

// content.js 文件

console.log("content script running"); // being logged to console
chrome.runtime.onMessage.addListener(
     async function(request, sender, sendResponse) {
      console.log(sender.tab ?
                  "from a content script:" + sender.tab.url :
                  "from the extension");
                //   console.log(request);
      if (request.greeting === "hello")
         await sendResponse({farewell: "goodbye"});
    }
  );
        

//弹出.html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Extension</title>
    <link rel="stylesheet" href="popup.css" />
  </head>
  <body>
    <h1>extension</h1>

    <input id="message-field" type="text" placeholder="enter message" />
    <button>Send message</button>

    <script src="popup.js"></script>
  </body>
</html>

有几个问题。

  • 当弹出窗口的开发工具集中时,Chrome 中的一个错误会破坏 chrome.tabs.query,更多信息

  • chrome.runtime.onMessage 侦听器无法在 Chrome 中使用async声明,更多信息

  • 安装/更新扩展时,其新内容脚本不会自动注入到 Chrome/ium 中当前打开的选项卡中,因此您必须自己明确地执行此操作,如此处所示,但在以下情况下有更好的选择你的,只有在用户调用扩展后才需要访问页面:通过 executeScript 进行编程注入

    • 删除 content.js
    • 从 manifest.json 中删除content_scripts
    • 从“权限”中删除“制表符”——这不是必需的,现在不会有关于观察浏览器历史记录的警告。
    • 将“脚本”添加到“权限”。
document.querySelector('button').onclick = async () => {
  // workaround for devtools window https://crbug.com/462939
  const { id: windowId } = await chrome.windows.getCurrent();
  const [tab] = await chrome.tabs.query({ active: true, windowId });
  let result;
  try {
    [{ result }] = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      // this runs in the web page, so it can't see variables in scope like `tab` 
      func: (param1, param2) => {
        return document.documentElement.innerHTML;
        // return {it: 'can', be: ['an object', 'too']};
      },
      // this is sent to the func's param1 and 2
      args: [123, { foo: 'bar' }],
    });
  } catch (err) {
    // the tab is not injectable
    console.warn(err);
    return;
  }
  console.log(result); // printing in the popup's devtools console
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM