Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 277
dbkk Avatar asked Sep 26 '13 17:09

dbkk


People also ask

How do I send an HTTP POST request from a Chrome extension?

Type the url in the main input field and choose the method to use: GET/POST/PUT/DELETE/PATCH. Click on the arrow "Send" or press Ctrl+Enter. You'll see info about the response (time, size, type) and you'll be able to see the content response in the response section.

How do you send a message to content script in Chrome?

If you only need to send a single message to another part of your extension (and optionally get a response back), you should use the simplified runtime. sendMessage or tabs. sendMessage. This lets you send a one-time JSON-serializable message from a content script to extension, or vice versa, respectively.

Can I copy text from a Chrome extension?

Click on Add to Chrome > Add Extension. Step 2: Open the website which has the protected text, click on the extension icon on the top right corner, and click on the Copyfish extension. Step 3: The extension provides you with a tool to select the area in which the text you want to copy is present.


2 Answers

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.

like image 179
Matthew Gertner Avatar answered Oct 08 '22 18:10

Matthew Gertner


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"}, "*")
like image 20
Hender Avatar answered Oct 08 '22 19:10

Hender