【问题标题】:using Gmail Api in chrome extension in content scripts在内容脚本的 chrome 扩展中使用 Gmail Api
【发布时间】:2017-04-22 02:28:22
【问题描述】:

我尝试在 JS 中创建一些 chrome 扩展,我需要在我的内容脚本中的扩展上使用 Gmail API。 我正在尝试使用gmail.js gitHub 库和inboxSdk 来使用它。

所以,我在 background.js 文件中创建了 oauth2,并尝试在我的 content.js 文件中使用 gapi.client.gmail .. 但无论我尝试什么,它始终是未定义的 gapi.client。 加载 Api 后,我成功在 background.js 页面中发送请求并从 Gmail API 获取响应,但在内容脚本中没有。

这是我的清单文件:

{
"name": "Example Gmail Extension",
 "content_scripts": [
  {
    "matches": [
     "https://mail.google.com/*",
     "http://mail.google.com/*" ],  
    "js": ["inboxsdk.js","content.js"],
    "run_at": "document_end"
  }
],  
"background": {
  "scripts": ["background.js" ,"client.js"]
},
"content_security_policy": "script-src https://*.google.com 'unsafe-eval';       object-src 'self'",
"oauth2": {
  "client_id": <clientid>,
  "scopes": ["https://www.googleapis.com/auth/gmail.modify"] 
 },
"permissions": [
    "background",
    "identity",
    "storage",
    "https://www.googleapis.com/*",
    "https://*.googleusercontent.com/*",
     "https://mail.google.com/",
     "http://mail.google.com/" ], 
 "manifest_version": 2
 }

当 client.js 包含用于 javaScript 的 Gmail API 库时。 我使用这个Loading Google API Javascript Client Library into Chrome Extension 来加载它。

我的背景文件只包含 oauth 和 Gmail Api 的负载 .. 当它被加载时,它是 recgonize gapi.client 并且我可以创建请求并获得响应。

chrome.identity.getAuthToken(
{'interactive': true},
function(token){
}  

window.gapi_onload = function(){
gapi.auth.authorize(
    {
        client_id: '<clientid',
        immediate: true,
        scope: 'https://www.googleapis.com/auth/gmail.modify'
    },
    function(){
      gapi.client.load('gmail', 'v1', function(){ 

       *here I sucess to call to gmail API with gapi.client....* 
    });
    }
);

我做错了吗? 我也尝试在内容脚本中设置 client.js,但这不是帮助相同的错误。

谢谢大家。

【问题讨论】:

  • 当您加载并执行您的扩展程序时,various appropriate consoles for your extension 中显示的究竟是什么?
  • gapi 未定义..
  • here 所述,您只能通过调用executeScript 或在清单中声明它们来在内容脚本上下文中加载内容; GAPI 将尝试使用&lt;script&gt; 注入方法加载更多库。您也可以查看此related SO post,它提供了示例代码 sn-p,这可能会有所帮助。

标签: javascript google-chrome-extension gmail gmail-api


【解决方案1】:

虽然方便,但不需要 Google 的 Javascript 客户端库 (gapi.*) 从您的扩展程序中调用 Google API。事实上,使用那个库可能不是一个非常好的主意。您必须添加“unsafe-eval”策略(由于某种原因它被称为不安全),然后动态加载 gapi 脚本(您在代码中没有这样做,这可能是您的麻烦的根本原因)或或者将 gapi 库打包到您的扩展中,这纯粹从软件生命周期的角度来看是个坏主意。

底线:您应该使用 XMLHttpRequest 或(最好)HTML5 Fetch API 直接调用 HTTP(“REST”)Google API。

【讨论】:

  • 谢谢。我认为你是对的。最好的办法是在 background.js 页面中获取用户令牌并将其转发到内容脚本,然后为 gmail API 创建 XMLHttpRequest 请求。无论如何,我可以在这里得到一些回答我的问题:Here。他们在那里说:“您不能在内容脚本中使用 Gmail.js API。如果您需要在浏览器上下文、内容脚本和后台脚本中进行单独处理,您将需要依赖跨上下文消息传递。 ... "
猜你喜欢
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 2016-08-25
  • 2011-09-28
相关资源
最近更新 更多