javascript - 在内容脚本的 chrome 扩展中使用 Gmail Api

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

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

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

这是我的 list 文件:

{
"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 的负载。当它加载时,它会识别 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,但这并没有帮助——同样的错误。

谢谢大家。

最佳答案

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

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

关于javascript - 在内容脚本的 chrome 扩展中使用 Gmail Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41012489/

相关文章:

javascript - 很难将 json 字符串从服务器转换为数组

Php 邮件程序 google smtp 在本地主机上工作,但无法在实时站点上工作

javascript - 将 ERB HTML 从 Rails 渲染为 Angular,Angular 尝试将其解释为 JSON

javascript - 跨网络应用程序和 Chrome 扩展程序共享本地存储对象

javascript - 内容脚本仅在重新加载/刷新时加载

javascript - 内容脚本看到错误的文档元素

python - 使用 Google API 获取用户电子邮件的最佳方式是什么?

email - 如何将Zend_Mail_Transport_Smtp与托管的Google Apps结合使用?

javascript - 如何删除 'back'按钮/如何保留后退按钮

javascript - 动态添加输入字段并跟踪输入的内容