简体   繁体   中英

Load Google JavaScript Client library in Meteor

I am trying to load the Google Client Library to use Google Calendar in my Meteor application but my callback ( onload=handleClientLoad ) function is not executing. The same is working when using from simple HTML +JavaScript app. I have also registered my Meteor application URL localhost:3000 in Google authorize URLs.

Template.hello.events({
    'click button': function () {
        callGoogle();
    }
});


function callGoogle() {
    jQuery.ajax({
        url: 'https://apis.google.com/js/client.js?onload=handleClientLoad',
        dataType: 'script',
        success: function () {
            console.log("Success");

        },
        error: function (e) {
            console.log("Error")
        },
        async: true
    });

    return false;
}

//This function is not executing
function handleClientLoad() {
    console.log("handleClientLoad");

    gapi.client.setApiKey(apiKey);
    window.setTimeout(checkAuth, 2);
}

function checkAuth() {
    gapi.auth.authorize({
        client_id: clientId,
        scope: scopes,
        immediate: false
    }, handleAuthResult);
}

function handleAuthResult(authResult) {

    console.log("authResult", authResult);
    if (authResult && !authResult.error) {
        gapi.client.load('calendar', 'v3', listUpcomingEvents);
    }
}

function listUpcomingEvents() {
    var request = gapi.client.calendar.events.list({
        'calendarId': 'primary',
        'timeMin': (new Date()).toISOString(),
        'showDeleted': false,
        'singleEvents': true,
        'maxResults': 10,
        'orderBy': 'startTime'
    });

You need to export your function to the global scope :

handleClientLoad = function() {
  console.log("handleClientLoad");
  gapi.client.setApiKey(apiKey);
  window.setTimeout(checkAuth, 2);
};
Just Add reference to google API in main HTML
<script src="https://apis.google.com/js/client.js"> </script>

Later on whenever you want to use gapi object you just need to set authentication parameters like below

var user=Meteor.user();
gapi.auth.setToken({
                        access_token: user.services.google.accessToken
                });
//Once you have set token to gapi, load calendar and on success do insert, read, edit etc

var ret = gapi.client.load('calendar', 'v3', function (error, result) {

                 }

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM