gmail-chrome-extension-boilerplate icon indicating copy to clipboard operation
gmail-chrome-extension-boilerplate copied to clipboard

Communication with background script

Open brandonhilkert opened this issue 10 years ago • 2 comments

This isn't an issue with the library itself, but just hoping to get you feedback. If the content script was just a normal script and didn't embed js links in the dom, you could communicate with a background script using:

    chrome.runtime.sendMessage data, (response) ->

However, if you embed the main.js in to the and I define some behavior on the read_email event, I need to send some messages to a background script. Because I'm now in the actual tab, not in the content script, I haven't been able to use chrome.runtime.sendMessage because it seems like it's out of context of the extension at that point.

Do you have suggestions on getting back in to the extension?

brandonhilkert avatar Sep 15 '14 11:09 brandonhilkert

This link demonstrates what I think you are trying to achieve. This is devtools specific, but the concept is the same for injected scripts. You can add window.postMessage to main.js, and listen for the message in the content.js

diagram adapted from that link:

main.js
     |
     | window.postMessage()
     V
content.js
     |
     | chrome.runtime.sendMessage()
     V
background script

psimyn avatar Jul 14 '15 23:07 psimyn

More info here as well: http://stackoverflow.com/questions/25838804/gmail-extension-sendmessage-to-background-from-page-context

jawspeak avatar Dec 15 '16 23:12 jawspeak