이전글 - Javascript로 GA 데이터 뽑아오기[1] : https://aljshal.tistory.com/29?category=743241



여러 사이트를 관리하고 있다면, 아래와 같이 배열을 이용하여 여러번 호출 하여 출력 하면 된다.

단, 사이트의 ids를 알아야 함 - ( https://ga-dev-tools.appspot.com/query-explorer/ 참고 )


<script>
    var gaArr = {
        "test1": "ga:123",
        "test2": "ga:456",
        "test3": "ga:789"
    };


<!-- 중략 - Javascript로 GA 데이터 뽑아오기[1] 참조 -->

    function handleProfiles(response) {
        // Handles the response from the profiles list method.
        if (response.result.items && response.result.items.length) {
            // Get the first View (Profile) ID.
            var firstProfileId = response.result.items[0].id;

            // Query the Core Reporting API.
            // queryCoreReportingApi(firstProfileId);

            $.each(gaArr, function (key, value) {
                query_ga(key, value);
            });

        } else {
            console.log('No views (profiles) found for this user.');
        }
    }

    function query_ga(key, value) {
        gapi.client.analytics.data.ga.get({
            'ids': value,
            'start-date': '2016-01-01',
            'end-date': '2019-03-24',
            'metrics': 'ga:sessions',
            'dimensions': 'ga:yearMonth',
            'sort': 'ga:yearMonth'
        })
        .then(function (response) {

            // 데이터 출력
            var formattedJson = JSON.stringify(response.result.rows, null, 2);
            if ($("#ga" + key).length == 0)
                $("#g-analyics").append("<h3>" + key + "</h3><div id='ga" + key + "'></div>");

            $("#ga" + key).html(formattedJson);
        })
        .then(null, function (err) {
            console.log(err);
        });
    }

    // Add an event listener to the 'auth-button'.
    document.getElementById('auth-button').addEventListener('click', authorize);
</script>

<script src="https://apis.google.com/js/client.js?onload=authorize"></script>



출력화면



+ Recent posts