admin管理员组

文章数量:1188420

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: .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?

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?

Share Improve this question edited Sep 15, 2014 at 11:41 Xan 77.5k18 gold badges196 silver badges216 bronze badges asked Sep 14, 2014 at 22:53 brandonhilkertbrandonhilkert 4,4757 gold badges26 silver badges39 bronze badges 3
  • 1 Unclear what you are asking. – Xan Commented Sep 15, 2014 at 6:18
  • Sorry...this has some more detail: github.com/KartikTalwar/gmail-chrome-extension-boilerplate/… – brandonhilkert Commented Sep 15, 2014 at 11:01
  • Aha, now I get it. You need to message your background from page context. – Xan Commented Sep 15, 2014 at 11:03
Add a comment  | 

2 Answers 2

Reset to default 23

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.

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);

本文标签: javascriptGmail ExtensionsendMessage to background from page contextStack Overflow