Gmail扩展,sendMessage从页面上下文背景 [英] Gmail Extension, sendMessage to background from page context

查看:142
本文介绍了Gmail扩展,sendMessage从页面上下文背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个扩展程序,以便与Gmail集成并通过将gmail.js注入页面上下文与Gmail集成,如下所示: https://github.com/KartikTalwar/gmail-chrome-extension-boilerplate/blob/master/content.js

这似乎是使用Google嵌入到页面中的全局变量的唯一显而易见的方式。



所以现在,我需要回到扩展的一些功能。在正常情况下(通过内容脚本运行),我会向后台脚本发送消息,但是甚至可以从标签本身的上下文中获得消息?

解决方案

页面上下文脚本确实无法使用Chrome API。

但是,它可以分派内容脚本可以捕获的DOM事件。



文档中有一个示例这里。除了使用 window.postMessage ,你可以调度自定义事件

因此,您需要让内容脚本像页面之间的代理一样工作上下文和背景。

  //内容脚本
//监听事件
window.addEventListener (PassToBackground,function(evt){
chrome.runtime.sendMessage(evt.detail);
},false);

//页面上下文
var message = {/ * whatever * /};
var event = new CustomEvent(PassToBackground,{detail:message});
window.dispatchEvent(event);

您可以将此概括为传回答案。


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?

解决方案

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.

这篇关于Gmail扩展,sendMessage从页面上下文背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆