Gmail extension, sendMessage for background from page context

I am creating an extension for integrating with Gmail and integrating with Gmail by injecting gmail.js into the page context as shown here: https://github.com/KartikTalwar/gmail-chrome-extension-boilerplate/blob/master/content.js

This is apparently the only obvious way to use some of the global variables that Google implements on the page.

So, now I need to return to some extension functions. Under normal conditions (using the contents of the script) I would send a message to the script background, but is this possible from the context of the tab itself?

+2
javascript google-chrome google-chrome-extension gmail
source share
2 answers

The script page context cannot use the Chrome API. However, it can send DOM events that can be captured by script content.

The documentation is here . Besides using window.postMessage , you can send custom events .

So you have to make your content script work as a proxy between the page context and the background. Something like that:

 // Content script //Listen for the event window.addEventListener("PassToBackground", function(evt) { chrome.runtime.sendMessage(evt.detail); }, false); // Page context var message = {/* whatever */}; var event = new CustomEvent("PassToBackground", {detail: message}); window.dispatchEvent(event); 

You can generalize this to convey a response.

+4
source share

Just a little for this, when using gmail.js, in order to receive a message from main.js on your extension page, you need to use your script content as an intermediary. This scheme, we hope, will illustrate.

 main.js | | window.postMessage(); | V content.js //window.addEventListener("message", callback, false); | | chrome.runtime.sendMessage(); | V background.js //chrome.runtime.onMessage.addListener(callback); 
+1
source share

All Articles