Home gapi.analytics.ready from Google Analytics Embed API does not called
Reply: 0

gapi.analytics.ready from Google Analytics Embed API does not called

Max E.
1#
Max E. Published in 2017-12-07 17:23:16Z

I am trying to embed some GA statistics in a page on Wordpress site. I am using server-side authorization. The sections with GA data does not render until I disable cache from Network tab in Google Developer Tools and refresh page. I added some debug console outputs and it shows that ready function is not executed at all when he page is viewed with "Disable cache" option disabled. Here is the code of my page:

    <?php

    require_once 'includes/google-api-php-client-2.2.1/vendor/autoload.php';

    get_header(); ?>

    <?php if ( ! is_front_page() ) : ?>

        <?php if ( function_exists( 'bcn_display' ) ) : ?>
        <div class="breadcrumbs">
            <?php bcn_display(); ?>
        </div>
        <?php endif; ?>

    <?php endif; ?>

    <div id="primary" class="content-area">
        <main id="main" class="site-main" role="main">

    <?php

    $client = new Google_Client();

    $client -> setAuthConfig(get_template_directory() . '/keys.json');

    $client -> setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

    if ($client -> isAccessTokenExpired()) {
          $client -> refreshTokenWithAssertion();
        }
    ?>

            <?php get_template_part( '/templates/titlebar' ); ?>

            <?php while ( have_posts() ) : the_post(); ?>

                <?php get_template_part( 'content', 'page' ); ?>

                <?php
                    // If comments are open or we have at least one comment, load up the comment template
                    if ( comments_open() || get_comments_number() ) :
                        comments_template();
                    endif;
                ?>

            <?php endwhile; // end of the loop. ?>

        </main><!-- #main -->
    </div><!-- #primary -->

    <?php get_sidebar(); ?>

<script>
google.load = google.load || google.charts.load;
(function(w,d,s,g,js,fjs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
  js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
console.log("gapi loaded");
</script> 

<script>
console.log("waiting for ready");
gapi.analytics.ready(function() {
  gapi.analytics.auth.authorize({
    'serverAuth': {
      'access_token': <?php echo "'" . $client -> getAccessToken()["access_token"] . "'"; ?>
    }
  });
console.log("authed");
var map = new gapi.analytics.googleCharts.DataChart({
  query: {
    'ids': 'ga:158047127',
    'dimensions': 'ga:country',
    'metrics': 'ga:sessions',
    'start-date': '30daysAgo',
    'end-date': 'yesterday',
  },
  chart: {
    type: 'GEO',
    container: 'map',
    options: {
      region: 'world',
      displayMode: 'regions',
      width: "100%"
    }
  }
});

  var table = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': 'ga:158047127',
      'dimensions': 'ga:country',
      'metrics': 'ga:sessions, ga:percentNewSessions, ga:newUsers, ga:pageviewsPerSession, ga:avgSessionDuration',
      'sort': '-ga:sessions',
      'start-date': '30daysAgo',
      'end-date': 'yesterday',
      'max-results': '100'
    },
    chart: {
      type: 'TABLE',
      container: 'table',
      options: {
        width: '100%'
      }
    }
  });

var tableRowClickListener;

table.on('success', function(response) {

    var chart = response.chart;
    var dataTable = response.dataTable;

    tableRowClickListener = google.visualization.events
        .addListener(chart, 'select', function(event) {

      if (!chart.getSelection().length) return;

      var row =  chart.getSelection()[0].row;
      var country =  dataTable.getValue(row, 0);
      var options = {
        query: {
          filters: 'ga:country==' + country

        },
        chart: {
          options: {
            title: country
          }
        }
      };

      map.set(options).execute();
    });
 });

map.execute();
table.execute();
console.log("rendered charts");
});
console.log("done!");
</script>

<?php get_footer(); ?>

Output from console in "normal" mode:

gapi loaded
waiting for ready
done!

Output from console when "Disable cache" option is enabled:

gapi loaded
waiting for ready
done!
authed
rendered charts

By the way, about auth token: is it ok, that I get a new auth token every time when I refresh the page? Should not it be used until expiration? Do I need to implement this logic and how to do it? An example with get_access_token() from https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/ does not manage token expiration too.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32429 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO