development

Google Analytics의 개발 작업을 조회수로 삼는 방법이 있습니까?

big-blog 2020. 6. 24. 07:10
반응형

Google Analytics의 개발 작업을 조회수로 삼는 방법이 있습니까?


Google Analytics를 사용할 수 있도록 페이지 하단에 필요한 JavaScript를 추가했습니다. 유일한 문제는 그것이 모든 개발 작업을 히트로 간주한다는 것입니다. 아마도 하루에 백 번 그 페이지 중 일부를 볼 때 내 독서가 실제로 왜곡됩니다. 특정 IP 주소에서 끄는 방법이 있습니까, 아니면 내 빌드 프로세스에 빌드해야하므로 배포를 위해 빌드 할 때만 추가됩니까?


예, 웹 로그 분석 설정으로 이동하여 사이트를 수정하고 + 필터 추가를 사용하여 IP 주소를 제외하는 필터를 정의합니다.

과거 데이터는 필터가 적용된 상태에서 재생성되지 않으므로 앞으로 나아갈 수있는 이점 만 있습니다.


나는 자바 스크립트를 사용하는 간단한 접근법을 좋아합니다. 어디에서나 작동합니다.

<script type="text/javascript">
if (document.location.hostname.search("myproductiondomainname.com") !== -1) {

//google analytics code goes here

}
</script>

2014 년이지만 기존의 모든 솔루션에 여전히 만족하지 않습니다 ...

  • IP 필터에는 고정 IP 주소가 필요합니다. 집이나 커피 숍에서 일하는 경우 어떻게합니까?
  • 호스트 이름을 확인하면 개발 환경에서 적중이 제거되지만 라이브 사이트를 디버깅하는 경우 어떻게됩니까?
  • 서버 구성 편집이 번거롭고 고급이며 여러 도메인이 복잡합니다.
  • 선택 해제 확장 프로그램은 모든 웹 사이트의 조회수를 차단하거나 요청한 사람에 따라 전혀 방문하지 않습니다.

그래서 나는 내 자신의 브라우저 확장 프로그램을 만들었습니다 ... https://chrome.google.com/webstore/detail/lknhpplgahpbindnnocglcjonpahfikn

  • 내가가는 곳마다 날 따라와
  • 개발 환경과 라이브 / 퍼블릭 도메인에서 작동합니다.
  • 그것은 내가 개발하고있는 사이트와 나에게만 영향을 미칩니다.
  • 한 번의 클릭으로 켜거나 끕니다.
  • 실제로 분석에 데이터를 보내지 않는지 쉽게 확인할 수 있습니다.

선택한 도메인에 대해서만 항상 "개발자 쿠키"를 컴퓨터에 설정하여 작동합니다. 그런 다음 웹 로그 분석으로 데이터를 보내기 전에 스크립트에서이 쿠키를 확인하면됩니다. 확장 프로그램 설정에서 쿠키에 대한 고유 한 NAME 및 VALUE를 맞춤 설정합니다. 팀원이 쉽게 사용할 수 있으므로 개발자, 컨텐츠 제작자, 교정자 및 조직 내 모든 사람이 통계를 늘리지 않고도 페이지를 모두 볼 수 있습니다.

코드를 페이지에 넣는 방법의 예 ...

자바 스크립트

if (window.location.host==="mydomain.com" || window.location.host==="www.mydomain.com") {
   if (document.cookie.indexOf("COOKIENAME=COOKIEVALUE") === -1) {
      // Insert Analytics Code Here
   }
}

PHP

if ($_SERVER['HTTP_HOST']==="mydomain.com" || $_SERVER['HTTP_HOST']==="www.mydomain.com") {
   if (@$_COOKIE["COOKIENAME"] !== "COOKIEVALUE") {
      // Insert Analytics Code Here
   }
}

호스트 이름이 실제 사이트의 도메인 ( "mydomain.com")과 같은지 확인하면 "localhost"또는 "beta.mydomain.com"과 같은 테스트 도메인에서 보는 동안 모든 방문자가 분석 데이터를 보내지 않습니다. . 위의 예에서 "www.mydomain.com"및 "mydomain.com"은 방문을 기록하려는 두 개의 유효한 도메인입니다.

라이브 사이트는 값이 일치하는 개발자 쿠키가없는 한 예상대로 데이터를 분석에 보냅니다. 기기에 고유 한 쿠키가 설정되어 있으면 Google 웹 로그 분석 또는 선호하는 다른 분석 도구의 총계에 대한 방문이 계산되지 않습니다.

솔루션을 공유하고 확장 프로그램을 사용하여 쿠키를 유지하십시오.


고정 IP를 사용하지 않는 경우 GA에서 IP 필터를 설정하면 도움이되지 않습니다.

환경 변수를 설정하고 조건부로 표시하십시오. 예를 들어 다음 Ruby on Rails 코드를 사용하십시오.

<% unless RAILS_ENV == "development" %>
    <!-- your GA code -->
<% end %>

모든 운영 체제에서 사용하는 모든 언어 / 프레임 워크로이 동작을 확장 할 수 있습니다. PHP에서는 getenv 함수를 사용할 수 있습니다 . 환경 변수 에 대한 Wikipedia 페이지에서 시스템 진행 방법을 확인하십시오.


NAT 뒤에 있거나 다른 이유로 IP를 Google 웹 로그 분석에 제공 할 수없는 경우 가장 간단한 방법은 브라우저를 열 때부터 Google 웹 로그 분석 도메인을 로컬 호스트 (127.0.0.1)로 설정하는 것입니다. Google 웹 로그 분석은 Google 웹 로그 분석에 대한 지식없이 작업 스테이션으로 전달됩니다.


개발 및 QA 작업을위한 두 번째 Google 웹 로그 분석 추적 코드를 설정했습니다. 실제로 분석 통합을 테스트하고 싶을 때 유용하며, 생산 통계를 피할 수 없습니다.


이 코드를 사용할 수 있습니다

<script>
var host = window.location.hostname;
if(host != "localhost")
{
    // your google analytic code here
}
</script>

해결책은 Google 태그 관리자 (GTM)를 사용하여 Google 웹 로그 분석을 처리하는 것입니다. 그러면 사이트 코드에 조건을 쓰지 않고도 프로덕션 도메인에서 Google 웹 로그 분석 만 실행할 수 있습니다. 방법은 다음과 같습니다.

GTM에서 페이지 호스트 이름에 프로덕션 도메인이 포함 된 경우에만 발생하는 트리거를 설정하십시오.

여기에 이미지 설명을 입력하십시오

그런 다음 범용 웹 로그 분석에 대한 태그를 설정하고 방금 만든 트리거를 트리거로 설정하십시오.

여기에 이미지 설명을 입력하십시오


https://chrome.google.com/webstore/detail/fadgflmigmogfionelcpalhohefbnehm 과 같이 Chrome 확장 프로그램이 몇 가지 있습니다.

고정 IP 주소가 아닌 경우 매우 편리합니다.


해당 웹 속성 ID에 대한 추적을 비활성화하려면 Google 웹 로그 분석 비동기 코드가 실행되기 전에이 행을 추가하십시오.

window['ga-disable-UA-XXXXXX-Y'] = true;

UA-XXXXXX-Y 추적을 사용 중지하려는 웹 속성 ID에 해당합니다.

보낸 사람 : https://developers.google.com/analytics/devguides/collection/gajs/


Firefox 용 Ad Blocker를 사용하는데, 특히 Google 웹 로그 분석 추적 스크립트를 차단할 수 있습니다. 파이어 폭스는 기본 개발 브라우저이므로 다른 브라우저에서 작업을 테스트해야 할 때까지 훌륭하게 작동합니다.


이 모든 트래픽을 필터링 하려면 맞춤 측정 항목사용하세요 .

앱에서 GA를 초기화 할 때 개발자를 추적하도록 맞춤 플래그를 설정하세요.

// In your header, after the GA code is injected
if( <your_code_to_check_if_is_dev> ) {
  ga('set', 'is_developer', 1 );
}

그런 다음 GA 계정에 필터를 추가하여 이러한 결과를 제거하십시오.

관리> 계정> 모든 필터> 필터 추가> 사용자 정의

여기에 이미지 설명을 입력하십시오


Probably not helpful to you, but I solved this problem by writing a custom ASP.NET server control that injects the required JavaScript. I then added the live URL to web.config and then only made the control visible when the host name matched the live URL in web.config.


Like people are mentioning you can either host the google-analytics.com domain locally or setup a function to see if you are working in your development network.

Keep in mind if http://www.google-analytics.com/ga.js does not load and your using onclick javascript functions to help track clicks on page elements.

IE: onclick="javascript:pageTracker._trackPageview('/made/up/folder/reference');

Your going to have JavaScript errors that will stop jQuery or other robust JavaScript functions from functioning.


이를위한 추가 옵션으로, 여러 사이트와 개발자가있는 개발 서버가 있습니다. 이것은 내가 세 가지 주요 옵션에 특히 만족하지 않았다는 것을 의미했습니다.

  • 많은 개발자에게 파일 문제가 있으며 사람의 실수에 노출
  • 모든 사이트 등에서 if / else 개발 블록
  • GA 웹 사이트 구성-일부 고객은 자체 GA 계정을 가지고 있습니다. 잊어 버리거나 간과 될 가능성이있는 모든 사이트 에서 완료 되어야합니다.

Rather than implementing the various options in the other answers here I approached the problem in the following way. In the global httpd.conf (rather than a site specific one) I used the apache module mod_substitute to simulate the effect the hosts file fix in another answer has, but for every development site, and every developer automatically.

Enable the module

CentOS: Open /etc/conf/httpd.conf and add the following line

LoadModule substitute_module modules/mod_substitute.so

Ubuntu/Debian: Run the following command

sudo a2enmod substitute

Once you've got the module enabled add the following lines to your httpd global config file

CentOS: /etc/conf/httpd.conf

Ubuntu/Debian: /etc/apache2/httpd.conf

# Break Google Analytics
AddOutputFilterByType SUBSTITUTE text/html 
Substitute "s|.google-analytics.com|.127.0.0.1|n"

Then restart apache

CentOS: service httpd restart

Ubuntu/Debian: /etc/init.d/apache2 restart

What this does is replace all text matching .google-analytics.com with .127.0.0.1 when apache serves the page so your page renders with analytics code similar to the below example

var _gaq = _gaq || [];
_gaq.push(['_setAccount', '']);
_gaq.push(['_trackPageview']);

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.127.0.0.1/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

I know this post is super old, but none of the solutions met my needs. Not only did I want to remove dev work from GA (and FB), but I also wanted to have some folks within the company not be counted in GA and FB. So I wanted a relatively easy method for those folks to exclude themselves from analytics without a plugin, or ruling out a domain ip (as folks with laptops wander).

I created a webpage that users can go to and click a link to opt out of the GA and FB tracking. It places a cookie for the site. Then I check that cookie to determine if we should send data to GA and FB.

I originally set this up on a site for called Dahlia, which is a boutique maker of items for Greek Orthodox Weddings and Baptisms.

Here's the code:

I put the following code in the header for all web pages:

<script>
//put in your google analytics tracking id below:
var gaProperty = 'UA-XXXXXXXX-X';

// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
  window[disableStr] = true;
  window['ga-disable-UA-7870337-1'] = true;  //This disables the tracking on Weebly too.
} else {
   //put in your facebook tracking id below:
  fbq('init', 'YYYYYYYYYYYYYYY');
  fbq('track', 'PageView');
}
</script>

Be sure to add your GA and FB tracking IDs in the spaces provided. This was originally written for a Weebly (shopping CMS) site. So if you are not on Weebly you can remove the line that mentions weebly.

Then I created a new webpage called "do-not-track" with the following code in the header:

<script>
//put in your own google analytics tracking id below:
var gaProperty = 'UA-XXXXXXXX-X';
var disableStr = 'ga-disable-' + gaProperty;

// Opt-out function
function gaOptout() {
  document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
  window[disableStr] = true;
  gaOptoutCheck();
}

// Check Opt-out function
function gaOptoutCheck() {
    var name = "ga-disable-"+gaProperty+"=";
    var ca = document.cookie.split(';');
    var found = "false";
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) found = "true";
    }
    if (found == "true") alert("Cookie is properly installed");
    else alert("COOKIE NOT FOUND");
}
</script>

And the following code in the body:

<a href="javascript:gaOptout()">Click here to opt-out of Google and Facebook Analytics</a>
<br><br>
Please visit this page on every computer, laptop, phone, tablet, etc. that you use; 
and for all browser you use on each of those devices.
<br><br>
If you ever remove cookies from browser, you will need to repeat this process for that browser.
<br><br><br>
<a href="javascript:gaOptoutCheck()">
Click to check if cookie is set</a>
<br><br>

Here is my full writeup for the Weebly site

Hope this helps somebody!


get the request host variable.

So wrap an if statement around the analytics javascript like this (Ruby-esque pseudocode):

<body>
<shtuff>dfsfsdf</shtuff>
if not (request.host == 'localhost')
  #analytics code here
elsif (request.host == the server's ip/domain)
  #analytics code here
else
  #do nothing
end
</body>

I have a PHP variable set for my local development that gives me a terminal for providing data/feedback etc when I'm working on stuff.

I use XAMPP so that has an env variable for tmp which is the following:

$isLocal = (getenv("tmp") == '\xampp\tmp') ? true : false;

This doesn't exist on my production server because xampp is not being used

if($isLocal){
  // do something, eg. load my terminal
}

... Specific to this question:

<?php if(!$isLocal){ ?>
  <!-- Insert Google Analytics Script Here -->
<?php } // end google analytics local check ?>

Today, whilst on a different computer than my own, I noticed μBlock Origin for Chrome was blocking Google AdSense by default. After some Googling, I found this article. It notes also μBlock Origin Firefox, μ Adblock for Firefox and Ad Muncher for Windows block AdSense by default. Most other options are listed as being configurable to block AdSense.

This seems to work and is useful because my IP is often dynamic, so the Chrome extension can follow me around as long as I am logged in to Chrome.

참고 URL : https://stackoverflow.com/questions/1251922/is-there-a-way-to-stop-google-analytics-counting-development-work-as-hits

반응형