Gmail Extension, sendMessage to background from page context Gmail Extension, sendMessage to background from page context google-chrome google-chrome

Gmail Extension, sendMessage to background from page context


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 eventwindow.addEventListener("PassToBackground", function(evt) {  chrome.runtime.sendMessage(evt.detail);}, false);// Page contextvar message = {/* whatever */};var event = new CustomEvent("PassToBackground", {detail: message});window.dispatchEvent(event);

You can generalize this to pass an answer back.


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(); | Vcontent.js //window.addEventListener("message", callback, false); | | chrome.runtime.sendMessage(); | Vbackground.js //chrome.runtime.onMessage.addListener(callback);