Gmail 扩展,从页面上下文向后台发送消息 [英] Gmail Extension, sendMessage to background from page context

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

问题描述

我正在构建一个扩展以与 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);}, 错误的);//页面上下文var message = {/* 随便 */};var event = new CustomEvent("PassToBackground", {detail: message});window.dispatchEvent(事件);

您可以对此进行概括以将答案传回.

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 扩展,从页面上下文向后台发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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