来自 Chrome 扩展程序的 Google 日历 API HTTP 请求

use*_*132 4 google-calendar-api google-chrome-extension

我正在为我的 chrome 扩展使用react-chrome-redux 堆栈。我已经尝试过日历 API 中的 Javascript/Node.js 快速入门,但它们不起作用。

所以现在我尝试通过 Chrome Identity API 检索 oAuth2 令牌,然后发出 HTTP 请求来获取我的数据。

清单.json

"oauth2": {
    "client_id": "CLIENT_ID.apps.googleusercontent.com",
    "scopes": [
      "https://www.googleapis.com/auth/calendar",
      "https://www.googleapis.com/auth/calendar.readonly"
    ]
  },
  "key": APP_KEY}
Run Code Online (Sandbox Code Playgroud)

HTTP请求

chrome.identity.getAuthToken({ 'interactive': false }, function(token) {
  var init = { 
    'method' : 'GET',
    'async'  : true,
    'headers': {
      'Authorization' : 'Bearer ' + token,
      'Content-Type': 'application/json'
    },
    'contentType': 'json'
  };

  fetch('https://www.googleapis.com/calendar/v3/calendars/public/events', init)
  .then((response) => response.json()) // Transform the data into json
  .then(function(data) {
      console.log(data);
    })
})
Run Code Online (Sandbox Code Playgroud)

我设法从 oAuth2 令牌中获取一长串字符,但是当我尝试发出 HTTP 请求时,收到 404 状态错误。

我在 Stack Overflow 上查找了很长时间,但大多数问题都没有得到很好的解答,而且似乎没有一种简单的方法可以通过 chrome 扩展使用 API。

我真的希望有人能帮助我,谢谢!

use*_*132 5

@furydevoid 弄清楚了,

结果默认日历关键字是“primary”而不是“public”

现在我对 HTTP 请求执行以下操作:

  const headers = new Headers({
      'Authorization' : 'Bearer ' + token,
      'Content-Type': 'application/json'
  })

  const queryParams = { headers };

  fetch('https://www.googleapis.com/calendar/v3/calendars/primary/events', queryParams)
  .then((response) => response.json()) // Transform the data into json
  .then(function(data) {
      console.log(data);
    })
  })
Run Code Online (Sandbox Code Playgroud)

对于任何尝试通过 Chrome 扩展使用 Google Calendar API 的人,

  1. Node.js 快速入门实际上不起作用,因为 Chrome 扩展实际上没有“后端”来执行脚本(至少对于我尝试过的)
  2. oAuth 之舞有点奇怪,因为在用户授予您权限后,您不能简单地将用户重定向到 Chrome://newtab,因为 Chrome://newtab 并未真正被识别为可以重定向到的安全网站或其他网站

无论如何,这是解决方案:

  1. 使用 Chrome 的身份 api 检索 oAuth2 令牌:https ://developer.chrome.com/apps/app_identity
  2. 如上所示,使用直接 HTTP 请求。

一切顺利!并感谢所有帮助过我的人!