Usare Google Calendar in Javascript

Mattepuffo's logo
Usare Google Calendar in Javascript

Usare Google Calendar in Javascript

Google mette a disposzione parecchie API per i suoi servizi; oggi vediamo come usare quelle per Google Calendar con Javascript all'interno delle nostre web app!

Il punto di partenza, per qualsiasi API, è creare un progetto; potete iniziare con il wizard ufficiale.

Poi andate nella sezione Libreria ed attivate le API che volete; sono richieste delle credenziali, che potete creare nella sezione Credenziali.

Create quelle di tipo OAuth scegliendo Applicazione web.

Quindi impostate il dominio Origine Javascript autorizzate; questo dipende da dove girerà la vostra web application; salvatevi l'ID client.

Adesso create un'altra credenziale di tipo Chiave API e salvatevi la chiave; anche qui, se volete, potete impostare dominio e restrizioni.

Per i test potete evitare, ma vi conviene impostarle in produzione per una questione di sicurezza.

Questo il codice completo della pagina:

<!DOCTYPE html>
<html>
    <head>
        <title>Google Calendar Javascript</title>
        <meta charset='utf-8'>
    </head>
    <body>
        <p>Google Calendar API Quickstart</p>
        <button id="authorize-button" style="display: none;">Authorize</button>
        <button id="signout-button" style="display: none;">Sign Out</button>
        <pre id="content"></pre>
        <script type="text/javascript">
            var CLIENT_ID = 'CLIENT_ID';
            var API_KEY = 'API_KEY';
            var DISCOVERY_DOCS = 
                    ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
            var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
            var authorizeButton = document.getElementById('authorize-button');
            var signoutButton = document.getElementById('signout-button');

            function handleClientLoad() {
                gapi.load('client:auth2', initClient);
            }

            function initClient() {
                gapi.client.init({
                    apiKey: API_KEY,
                    clientId: CLIENT_ID,
                    discoveryDocs: DISCOVERY_DOCS,
                    scope: SCOPES
                }).then(function () {
                    gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
                    updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
                    authorizeButton.onclick = handleAuthClick;
                    signoutButton.onclick = handleSignoutClick;
                });
            }

            function updateSigninStatus(isSignedIn) {
                if (isSignedIn) {
                    authorizeButton.style.display = 'none';
                    signoutButton.style.display = 'block';
                    listUpcomingEvents();
                } else {
                    authorizeButton.style.display = 'block';
                    signoutButton.style.display = 'none';
                }
            }

            function handleAuthClick(event) {
                gapi.auth2.getAuthInstance().signIn();
            }

            function handleSignoutClick(event) {
                gapi.auth2.getAuthInstance().signOut();
            }

            function appendPre(message) {
                var pre = document.getElementById('content');
                var textContent = document.createTextNode(message + 'n');
                pre.appendChild(textContent);
            }

            function listUpcomingEvents() {
                gapi.client.calendar.events.list({
                    'calendarId': 'primary',
                    'timeMin': (new Date()).toISOString(),
                    'showDeleted': false,
                    'singleEvents': true,
                    'maxResults': 10,
                    'orderBy': 'startTime'
                }).then(function (response) {
                    var events = response.result.items;
                    appendPre('Upcoming events:');
                    if (events.length > 0) {
                        for (i = 0; i < events.length; i++) {
                            var event = events[i];
                            var when = event.start.dateTime;
                            if (!when) {
                                when = event.start.date;
                            }
                            appendPre(event.summary + ' (' + when + ')')
                        }
                    } else {
                        appendPre('No upcoming events found.');
                    }
                });
            }
        </script>
        <script async defer src="https://apis.google.com/js/api.js"
                onload="this.onload = function () {};
                handleClientLoad()"
                onreadystatechange="if (this.readyState === 'complete') this.onload()">
        </script>
    </body>
</html>

Enjoy!


Condividi

1 Commenti

  • paolo

    praticamente hai copiato e incollato il codice della documentazione di google, quella ufficiale. XD

    20/04/2019

Commentami!