이전글

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

Javascript로 GA 데이터 뽑아오기[2] : https://aljshal.tistory.com/30?category=743241



위에서 뽑아낸 데이터를 차트로 보고자 하여, 'morris.js' 를 사용하였다.


<!-- morris --> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>



<div id="myfirstchart"></div> <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 list = new Array(); $.each(response.result.rows, function (i, j) { var data = new Object(); data.key = j[0]; data.value = j[1]; list.push(data); }); // String 형태로 변환 var jsonData = JSON.stringify(list); // 차트 출력 if ($("#myfirstchart-" + key).length == 0) $("#myfirstchart").append("<h3>" + key + "</h3><div id='myfirstchart-" + key + "' style='height: 200px;'></div>"); var chart = new Morris.Line({ element: 'myfirstchart-' + key, data: list, xkey: ['key'], ykeys: ['value'], labels: ['Value'], parseTime: false, }); }) .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>




출력화면


이전글 - 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>



출력화면



Google에서는 Open API를 제공하여 Google Analytics의 통계를 외부 페이지에 출력 할 수 있다.

단, 사전에 Google APIs에서 사용자 인증 정보를 등록하여 CLIENT_ID 를 알고 있어야 한다.

(이 부분은 다른 사이트를 구글링 하길 바란다.)



<button id="auth-button" hidden>Authorize</button> <h1>Hello Analytics</h1> <textarea cols="80" rows="20" id="query-output"></textarea> <script> // Replace with your client ID from the developer console. var CLIENT_ID = '[CLIENT_ID]'; // Set authorized scope. var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']; function authorize(event) { // Handles the authorization flow. // `immediate` should be false when invoked from the button click. var useImmdiate = event ? false : true; var authData = { client_id: CLIENT_ID, scope: SCOPES, immediate: useImmdiate }; gapi.auth.authorize(authData, function(response) { var authButton = document.getElementById('auth-button'); if (response.error) { authButton.hidden = false; } else { authButton.hidden = true; queryAccounts(); } }); } function queryAccounts() { // Load the Google Analytics client library. gapi.client.load('analytics', 'v3').then(function() { // Get a list of all Google Analytics accounts for this user gapi.client.analytics.management.accounts.list().then(handleAccounts); }); } function handleAccounts(response) { // Handles the response from the accounts list method. if (response.result.items && response.result.items.length) { // Get the first Google Analytics account. var firstAccountId = response.result.items[0].id; // Query for properties. queryProperties(firstAccountId); } else { console.log('No accounts found for this user.'); } } function queryProperties(accountId) { // Get a list of all the properties for the account. gapi.client.analytics.management.webproperties.list( {'accountId': accountId}) .then(handleProperties) .then(null, function(err) { // Log any errors. console.log(err); }); } function handleProperties(response) { // Handles the response from the webproperties list method. if (response.result.items && response.result.items.length) { // Get the first Google Analytics account var firstAccountId = response.result.items[0].accountId; // Get the first property ID var firstPropertyId = response.result.items[0].id; // Query for Views (Profiles). queryProfiles(firstAccountId, firstPropertyId); } else { console.log('No properties found for this user.'); } } function queryProfiles(accountId, propertyId) { // Get a list of all Views (Profiles) for the first property // of the first Account. gapi.client.analytics.management.profiles.list({ 'accountId': accountId, 'webPropertyId': propertyId }) .then(handleProfiles) .then(null, function(err) { // Log any errors. console.log(err); }); } 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); } else { console.log('No views (profiles) found for this user.'); } } function queryCoreReportingApi(profileId) { // Query the Core Reporting API for the number sessions for // the past seven days. gapi.client.analytics.data.ga.get({ 'ids': 'ga:' + profileId, 'start-date': '2019-03-18', 'end-date': '2019-03-24', 'metrics': 'ga:sessions' }) .then(function(response) { var formattedJson = JSON.stringify(response.result, null, 2); document.getElementById('query-output').value = formattedJson; }) .then(null, function(err) { // Log any errors. 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>



출력화면


일반적으로 css, js를 수정하면 브라우저에 캐시가 남아있어서 바로 적용이 되지 않는다.
CDN같은 경우에는 해당 업체를 통해서 캐시를 초기화하면 되지만, 브라우저에 남는 캐시는 유저가 직접 초기화를 해줘야 정상 작동을 한다.

하지만 아래와 같이 css와 js 뒤에 파라미터를 붙이면, 브라우저가 다른 파일로 인식하여 다시 캐싱한다.
<link rel="stylesheet" href="/common.css?ver=2018070401" type="text/css"></link>

이것을 자동으로 적용되게 하려면, 백단에서 수정날짜를 assign하여 뿌려주면 된다.
<?php
$cssVer = date('ymdHis',filemtime('/var/www/html/css/common.css')); 
        $this->context->smarty->assign(array( 
            'cssVer' => $cssVer, 
        ));
?>

<link rel="stylesheet" href="/common.css?ver={$cssVer}" type="text/css"></link>



+ Recent posts