5

I need to pass a message (raise an event) in a Chrome extension, and have JavaScript on a web page react to it.

In content_script.js of the extension, there should be a function like

raiseXYZevent(data);

JavaScript on the web page http://example.com/mypage.html should execute a handler

 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). Is there a way to make DOM changes from the extension, somehow detect them from the web page and call processXYZevent?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
dbkk
  • 12,288
  • 13
  • 51
  • 59

2 Answers2

6

Since the content script and the webpage share the same DOM, you can use postMessage to send messages between them. The Chrome API documentation explains this in detail with examples.

Matthew Gertner
  • 4,409
  • 2
  • 31
  • 54
1

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"}, "*")
Hender
  • 83
  • 7