Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'authorize' of undefined in Google Oauth?

I'm use Oauth for developing for chrome extension and user can login by Google Account.I have code jquery as below.

I'm also include js library in html file:

<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>

<script src="js/client.js"></script>  

and have JS function:

function handleAuthClick(event) {
gapi.auth.authorize({
    client_id: clientID,
    scope: scopes,
    response_type: 'code token id_token gsession',
    access_type: accessType,
    immediate: false
}, handleAuthResult);
return false;
}

My problem is: I can not login by google account and it show error : Uncaught TypeError: Cannot read property 'authorize' of undefined.

Note: If I'm run as html I can login normally, but I can not sign in when use as chrome extension.

like image 564
Icom2015 Avatar asked Oct 21 '22 06:10

Icom2015


1 Answers

It seems that gapi.auth is still not initialised and the reason for that is that you didn't follow the proper chain of steps to set it up before making this call. So I am just putting here a sample for you to see if you are missing any of the steps while initializing the gapi object successfully. Here it goes

<script type="text/javascript">
    (function( gapi ) {
        gapi.client.setApiKey(apiKey); // your variable for apiKey
        window.setTimeout(checkAuth,1);

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

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

      function handleAuthClick(event) {
          gapi.auth.authorize({
              client_id: clientID,
              scope: scopes,
              response_type: 'code token id_token gsession',
              access_type: accessType,
              immediate: false
          }, handleAuthResult);
          return false;
       }
     })( gapi );
</script>

You can safely put this script tag in your body tag just below the button html code.

like image 97
Akshay Chugh Avatar answered Oct 23 '22 16:10

Akshay Chugh