简体   繁体   English

将消息从 Chrome 扩展程序传递到网页

[英]Pass a message from Chrome Extension to Webpage

I need to pass a message (raise an event) in a Chrome extension, and have JavaScript on a web page react to it.我需要在 Chrome 扩展程序中传递消息(引发事件),并让网页上的 JavaScript 对其做出反应。

In content_script.js of the extension, there should be a function like在扩展的content_script.js中,应该有一个类似的函数

raiseXYZevent(data);

JavaScript on the web page http://example.com/mypage.html should execute a handler网页http://example.com/mypage.html上的 JavaScript 应该执行一个处理程序

 function processXYZevent(data) { ... }

The problem is that content script within an extension cannot interact with JavaScript on the web page directly (it can only modify DOM).问题是扩展中的内容脚本不能直接与网页上的 JavaScript 交互(它只能修改 DOM)。 Is there a way to make DOM changes from the extension, somehow detect them from the web page and call processXYZevent ?有没有办法从扩展中进行 DOM 更改,以某种方式从网页中检测它们并调用processXYZevent

Since the content script and the webpage share the same DOM, you can use postMessage to send messages between them.由于内容脚本和网页共享同一个 DOM,您可以使用postMessage在它们之间发送消息。 The Chrome API documentation explains this in detail with examples. Chrome API 文档通过示例详细解释了这一点。

From content script inject this:从内容脚本注入:

$('html').append(`
    <script>

      window.addEventListener("message", function(event) {
       // We only accept messages from ourselves
       if (event.source != window)
         return;

        if (event.data.type && (event.data.type == "FROM_CONTENT")) {
          console.log("Page script received: " + event.data.text)
          console.log(event.data.text) // "Something message here"
        }
      }, false)
    <\/script>`)

In content script you can execute this:在内容脚本中,您可以执行以下操作:

window.postMessage({ type: "FROM_CONTENT", text: "Something message here"}, "*")

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

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