简体   繁体   中英

Google Analytics Embed API gapi.analytics.auth.isAuthorized() always returns false

I am experimenting with embedding Google Analytics in my CMS. I want to check whether the user is authorized and if they are, I will display a 'sign out' button so that they can sign out and then sign in with a different Google account.

I have the sign out button working but I don't want it displayed unless the user is signed in.

According to the docs, this should work: gapi.analytics.auth.isAuthorized()

But when I log that to the console it always returns false.

Here's a bit more of my code:

gapi.analytics.ready(function() {

        /**
         * Authorize the user immediately if the user has already granted access.
         * If no access has been created, render an authorize button inside the
         * element with the ID "embed-api-auth-container".
         */
        gapi.analytics.auth.authorize({
            container: 'embed-api-auth-container',
            clientid: 'XXXXX'
        });

        console.log(gapi.analytics.auth.isAuthorized());

Please can someone tell me what I am doing wrong?

I'm a bit late with the answer but maybe will help someone.

Google analytics api uses OAuth 2.0 for authorization, and gapi.analytics.auth.isAuthorized() from your code always returns false because there is no currently authorized users.

You can easly check if there's authorized users:

var isAuthorized = gapi.analytics.auth.isAuthorized();

if(isAuthorized == true) {
  // display sign out button
}else {
  // display sign in button
}

If you already have an access token, you can include it authorize, and user will be signed in automatically:

gapi.analytics.auth.authorize({
    container: 'embed-api-auth-container',
    clientid: 'XXXXX',
    serverAuth: {
       access_token: 'XXXXX'
    }
});

and run check:

var isAuthorized = gapi.analytics.auth.isAuthorized();

if(isAuthorized == true) {
  // display sign out button
}else {
  // display sign in button
}

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