4

I am having trouble with fetching data from Google Analytics API with javascript. I can't seem to fetch anything but lets say its something basic like pageviews.

I am using Analytics.js

This is the code i am using to connect to GA API:

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'XXX', 'example.com');
    ga('send', 'pageview');

So how do i get the pageviews now? I tried using this code but it returns undefined:

ga(function() {
      var tracker = ga.getByName('t0');
      alert(tracker.get('page'));
    });

2 Answers 2

7

Analytics.js is a tracking API. It just tracks/sends data to Google Analytics.

In order to retrieve data from Google Analytics you need to use a different API. Look for the Reporting API.

https://developers.google.com/analytics/devguides/reporting/

Sign up to request clarification or add additional context in comments.

4 Comments

Eduardo, I have another question that might be relevant: Since GA get all this info about the demographics of the user, referal, etc... is ther a way that I can access that I can read that data at the moment of the visit? I mean, if I already have GA in the site and it has the data that my user is from Germany... I would prefer not to get that data from GA and not to add more .js's that can retrieve me this.
@GV3 Nope. That information is only available after Google has processed the data and finds the country based on ip ranges. This doesn't happen in real time, so at the time of the visit this info is not even available. You should use a different tool to get visitor Geolocation. Google Analytics is not a tool for that.
OK! but then again I see that in the REPORTING page of GA they have a LIVE reporting... can I not somehow query the same data that is there while my visitor is visiting so that I can have the same wished result ?
Nope, there's no API to access the data in the live reports yet. And when/if it comes out it will be a different api, not the same you use for tracking. To pull data you have to be authenticated as well so it won't be as simple as you imagine.
0

You can get variables you send as payload using tracker object.

For example:

ga(function(tracker) {
  var defaultPage = tracker.get('location');console.log(defaultPage);
});

(See analytics_debug.js for more information)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.