Google Calendar APIをJavaScriptで使う


準備

Google Consoleにログイン
アプリケーションを登録(Webアプリケーション)
※ただし、Redirect URIsは空にして登録すること!

後で使うのは

  • Client ID for web applicationsの欄のClient ID
  • Simple API Accessの欄のAPI key

認証処理

認証用のボタンを用意

<button id="authorize-button" style="visibility: hidden">Authorize</button>
var clientId = '準備したClientID';
var apiKey = '準備したAPI key';

// とりあえず、怖いので、カレンダーを読むだけの設定
// https://www.googleapis.com/auth/plus.meは不要かも。。

var scopes = ['https://www.googleapis.com/auth/plus.me',
                   'https://www.googleapis.com/auth/calendar.readonly'];

function handleClientLoad() {
        // 予めAPI Consoleで設定したAPIキーを設定
        gapi.client.setApiKey(apiKey);

        // すでに認証済みかの確認をする。
        window.setTimeout(checkAuth,1);
}

function checkAuth() {
        // immediateをtrueで指定することで、未認証の場合、ただちにエラーが返り、
        // handleAuthResultが呼び出される。
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
}

function handleAuthResult(authResult) {
        var authorizeButton = document.getElementById('authorize-button');
        if (authResult && !authResult.error) {
          authorizeButton.style.visibility = 'hidden';
          makeApiCall();
        } else {
          authorizeButton.style.visibility = '';
          authorizeButton.onclick = handleAuthClick;
        }
}

function handleAuthClick(event) {
        // ここで、ポップアップ画面を表示して、OAuth認証を行う。
        gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
        return false;
}

Google Calendar APIを使う

function makeApiCall() {
        var restRequest = gapi.client.request({
            'path': '/calendar/v3/users/me/calendarList'
        });
        restRequest.execute(function(calendarList) {
          console.dir(calendarList);
        });
}

ただ、現実的には...

カレンダーリストよりカレンダーIDを取得してこのIDを指定してイベントを取得する等の処理
を実装する必要がある。

さらに

イベントの取得で、デフォルトだと
日付の指定して取得した場合、繰り返しイベントの返され方が
イマイチであったりと、

そんなわけで、サンプル作ってみた

Qiitaの関連する投稿

関連記事