gapi is not defined error comes when using with requirejs

I am trying to load google API files with requireJS, but getting an error of, One think I can understated that GP file is loading before the google's call

"gp.js:23 Uncaught ReferenceError: gapi is not defined"

here is the code for

gp.js file

function logout()
{
    gapi.auth.signOut();
    location.reload();
}
function login() 
{
    var myParams = {
        'clientid' : '900278902057-ppqm358qrhki089danipqguj3i4ir70i.apps.googleusercontent.com',
        'cookiepolicy' : 'single_host_origin',
        'callback' : 'loginCallback',
        'approvalprompt':'force',
        'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'
    };
    gapi.auth.signIn(myParams);
}

function loginCallback(result)
{
    if(result['status']['signed_in'])
    {
        var request = gapi.client.plus.people.get(
            {
                'userId': 'me'
            });
        request.execute(function (resp)
                        {
            var email = '';
            if(resp['emails'])
            {
                for(i = 0; i < resp['emails'].length; i++)
                {
                    if(resp['emails'][i]['type'] == 'account')
                    {
                        email = resp['emails'][i]['value'];
                    }
                }
            }




            var str = "Name:" + resp['displayName'] + "<br>";
            //                str += "Image:" + resp['image']['url'] + "<br>";
            //    str += "<img src='" + resp['image']['url'] + "' /><br>";

            // str += "URL:" + resp['url'] + "<br>";
            str += "Email:" + email + "<br>";
            str += "DOB:" + resp['birthday'] + "<br>";
            str += "Gender:" + resp['gender'] + "<br>";
            document.getElementById("profile").innerHTML = str;
        });

    }

}
function onLoadCallback()
{
    gapi.client.setApiKey('AIzaSyBy08qpAjR9U1nKaZ5H1MmwTuthspQPNqY');
    gapi.client.load('plus', 'v1',function(){});
}

and also the requirejs file - main.js

require.config({
    shim: {

        'jquery': {
            exports: '$'
        },
/*        'backbone': {
            deps: ['jquery', 'underscore'],
        },*/
        'googleplus' : {
            deps: ['jquery'],
            exports: 'gapi'
        },


    },
    paths: {
        'jquery': '//code.jquery.com/jquery-1.11.0.min',
        'googleplus': 'https://apis.google.com/js/plus.js?onload=init',

    }
})
require(['gp']);

and the html buttons

 <input type="button"  value="Login" onclick="login()" />
<input type="button"  value="Logout" onclick="logout()" />

the same code works perfectly when I try without requireJS, but the thing is I have to do with requireJS

Answers:

Answer

gp.js must be a module.

define(['jquery', 'googleplus'], function($, gapi) {
    # your code

    window.loginCallback = function (result) {
        if (result['status']['signed_in']) {
            gapi.client.load('plus', 'v1', function () {
                var request = gapi.client.plus.people.get(
                    {
                        'userId': 'me'
                    });
                request.execute(function (resp) {
                    var email = '';
                    if (resp['emails']) {
                        for (i = 0; i < resp['emails'].length; i++) {
                            if (resp['emails'][i]['type'] == 'account') {
                                email = resp['emails'][i]['value'];
                            }
                        }
                    }


                    var str = "Name:" + resp['displayName'] + "<br>";
                    str += "Email:" + email + "<br>";
                    str += "DOB:" + resp['birthday'] + "<br>";
                    str += "Gender:" + resp['gender'] + "<br>";
                    document.getElementById("profile").innerHTML = str;
                });
            });
        }
    };

    $('#login').click(login);
    $('#logout').click(logout);
});

And modify template:

<input type="button"  value="Login" id="login" />
<input type="button"  value="Logout" id="logout" />

Because gapi.signIn method require callback function in global namespace, loginCallback function must be global.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.