Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gmail Extension, sendMessage to background from page context

I'm building an extension to integrate with Gmail and integrating with Gmail by injecting the gmail.js into the page context, as shown here: https://github.com/KartikTalwar/gmail-chrome-extension-boilerplate/blob/master/content.js

That seems to be the only obvious way to make use of some globals that Google is embedding on the page.

So now, I need to get back to some of the functionality of the extension. Under normal conditions (operating from a content script), I would send a message to the background script, but is that even possible from the context of the tab itself?

like image 627
brandonhilkert Avatar asked Sep 14 '14 22:09

brandonhilkert


People also ask

How can background scripts and content scripts communicate?

Communication between extensions and their content scripts works by using message passing. Either side can listen for messages sent from the other end, and respond on the same channel.

What is a content script?

A content script is a part of your extension that runs in the context of a particular web page (as opposed to background scripts which are part of the extension, or scripts which are part of the website itself, such as those loaded using the <script> element).


2 Answers

A page-context script cannot, indeed, use Chrome API.
It can, however, dispatch DOM events that can be caught by the content script.

There is an example in the documentation here. Besides using window.postMessage, you can dispatch custom events.

So, you need to make your content script to work like a proxy between page context and background. Something along these lines:

// 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 pass an answer back.

like image 139
Xan Avatar answered Oct 18 '22 08:10

Xan


Just to expand on this a bit, when using gmail.js, in order to get a message from main.js to your extension page, you need to use your content script as an intermediary. This diagram will hopefully illustrate.

main.js
 |
 | window.postMessage();
 |
 V
content.js //window.addEventListener("message", callback, false);
 |
 | chrome.runtime.sendMessage();
 |
 V
background.js //chrome.runtime.onMessage.addListener(callback);
like image 38
Tom Avatar answered Oct 18 '22 09:10

Tom