Monday, May 20, 2024
186
rated 0 times [  192] [ 6]  / answers: 1 / hits: 5274  / 10 Years ago, sun, september 14, 2014, 12:00:00

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?


More From » google-chrome

 Answers
3

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.


[#42512] Friday, September 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
austonjuancarlosb

Total Points: 238
Total Questions: 89
Total Answers: 99

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;