user6679132
user6679132

Reputation: 91

Google Calendar API HTTP request from a chrome extension

I'm using a react-chrome-redux stack for my chrome extension. I've tried the Javascript / Node.js quickstarts from the Calendar API but they don't work.

So now I'm trying to retrieve the oAuth2 token via Chrome Identity API, then making a HTTP request to get my data.

manifest.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}

HTTP request

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);
    })
})

I manage to get a long string of characters from the oAuth2 token, but when I try to make the HTTP request, I get a 404 status error.

I've looked for a long time on Stack Overflow but most questions were not well answered, and there doesn't seem to be a simple way to use the API from a chrome extension.

I really hope someone can help me out here, thanks!

Upvotes: 4

Views: 2963

Answers (1)

user6679132
user6679132

Reputation: 91

@furydevoid figured it out,

Turns out the default calendar keyword is 'primary' and not 'public'

So now I'm doing this for the HTTP request:

  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);
    })
  })

For anyone trying to use the Google Calendar API from a chrome extensions,

  1. The Node.js quickstart doesn't really work because Chrome extensions don't really have a 'backend' to execute the scripts (at least for what I tried)
  2. The oAuth dance is a little wonky because you can't simply redirect the user to Chrome://newtab after they've given you permissions, because Chrome://newtab is not really recognised as a safe site to redirect to or something

Anyway here's the solution:

  1. Use Chrome's identity api to retrieve the oAuth2 token: https://developer.chrome.com/apps/app_identity
  2. Use make a direct HTTP request as demonstrated above.

All the best! And thanks to everyone who helped me!

Upvotes: 5

Related Questions