如何从代码中触发Google Analytics?

时间:2021-09-08 13:50:27

My app reads an (html) file from my website, and I would like to track accesses to that file using Google Analytics. As the GA Javascript does not get executed when reading the file, it is not tracked. Is there a way to trigger GA directly from code or alternatively, to execute the Javascript from a .NET app without adding a bunch of dependencies?

我的应用程序从我的网站上读取(html)文件,我想使用Google Analytics跟踪对该文件的访问。由于GA Javascript在读取文件时未执行,因此不会对其进行跟踪。有没有办法直接从代码触发GA,或者从.NET应用程序执行Javascript而不添加一堆依赖项?

6 个解决方案

#1


7  

Google Analytics works by making a webrequest through javascript back to Google's server. If you want to do this programmatically, you just have to make this web request yourself. I would use Fiddler or FireBug to capture what the request looks like when you load the page in your browser. Then you can use that same URL in your .Net app.

Google Analytics(分析)的工作原理是通过javascript将网络请求发回Google的服务器。如果您想以编程方式执行此操作,则只需自己制作此Web请求即可。我会使用Fiddler或FireBug来捕获在浏览器中加载页面时请求的样子。然后,您可以在.Net应用中使用相同的URL。

#2


5  

I have recently released a .net library that allows you to natively log a page view with Google Analytics through code. It is released as open source under GNU so all that is required is proper attribution.

我最近发布了一个.net库,允许您通过代码使用Google Analytics本地记录页面视图。它在GNU下作为开源发布,所以所需要的只是正确的归属。

You can get the library here: http://www.diaryofaninja.com/projects/details/ga-dot-net

您可以在这里获取图书馆:http://www.diaryofaninja.com/projects/details/ga-dot-net

example usage of the API:

API的示例用法:

GooglePageView pageView = new GooglePageView("My page title",
                                "www.mydomain.com",
                                "/my-page-url.html");
TrackingRequest request = new RequestFactory().BuildRequest(pageView);
GoogleTracking.FireTrackingEvent(request);

There is also a built in HTTP Handler that allows you to fire tracking events by simply including a tracking pixel on the page:

还有一个内置的HTTP处理程序,允许您通过在页面上包含跟踪像素来触发跟踪事件:

<img src="/tracker.asmx?domain=mydomain.com&pagetitle=My%20Page%20Title&url=/my-page.aspx" />

Alternatively you can use jquery to track links within a page using Google Analytics (zip, jpg, etc) - blogged about it a while ago here:

或者,您可以使用jquery使用Google Analytics(zip,jpg等)跟踪页面中的链接 - 不久之前在此博客:

http://www.diaryofaninja.com/blog/2009/09/17/random-file-zip-and-pdf-tracking-using-jquery-amp-google-analytics

http://www.diaryofaninja.com/blog/2009/09/17/random-file-zip-and-pdf-tracking-using-jquery-amp-google-analytics

#3


3  

private void analyticsmethod4(string trackingId, string pagename)
{
    Random rnd = new Random();

    long timestampFirstRun, timestampLastRun, timestampCurrentRun, numberOfRuns;

    // Get the first run time
    timestampFirstRun = DateTime.Now.Ticks;
    timestampLastRun = DateTime.Now.Ticks-5;
    timestampCurrentRun = 45;
    numberOfRuns = 2;

    // Some values we need
    string domainHash = "123456789"; // This can be calcualted for your domain online
    int uniqueVisitorId = rnd.Next(100000000, 999999999); // Random
    string source = "Shop";
    string medium = "medium123";
    string sessionNumber = "1";
    string campaignNumber = "1";
    string culture = Thread.CurrentThread.CurrentCulture.Name;
    string screenRes = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;


    string statsRequest = "http://www.google-analytics.com/__utm.gif" +
        "?utmwv=4.6.5" +
        "&utmn=" + rnd.Next(100000000, 999999999) +
    //  "&utmhn=hostname.mydomain.com" +
        "&utmcs=-" +
        "&utmsr=" + screenRes +
        "&utmsc=-" +
        "&utmul=" + culture +
        "&utmje=-" +
        "&utmfl=-" +
        "&utmdt=" + pagename +
        "&utmhid=1943799692" +
        "&utmr=0" +
        "&utmp=" + pagename +
        "&utmac=" +trackingId+ // Account number
        "&utmcc=" +
            "__utma%3D" + domainHash + "." + uniqueVisitorId + "." + timestampFirstRun + "." + timestampLastRun + "." + timestampCurrentRun + "." + numberOfRuns +
            "%3B%2B__utmz%3D" + domainHash + "." + timestampCurrentRun + "." + sessionNumber + "." + campaignNumber + ".utmcsr%3D" + source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium + "%7Cutmcct%3D%2Fd31AaOM%3B";


    using (var client = new WebClient())
    {
        client.DownloadData(statsRequest);
        //Stream data = client.OpenRead(statsRequest);
        //StreamReader reader = new StreamReader(data);
        //string s = reader.ReadToEnd();
    }

}

refer this - http://tilr.blogspot.com/2012/10/google-analytics-use-google-analytics.html

请参阅此内容 - http://tilr.blogspot.com/2012/10/google-analytics-use-google-analytics.html

#4


2  

Google Analytics provides two way to track custom actions, events, or whatever you deal with. In your case, the trivial solution is to generate a virtual pageview for the HTML file your application reads in. Call the appropriate JavaScript function:

Google Analytics提供了两种跟踪自定义操作,事件或您处理的内容的方法。在您的情况下,简单的解决方案是为您的应用程序读入的HTML文件生成虚拟页面视图。调用相应的JavaScript函数:

pageTracker._trackPageview("/Foo.html");

This way every time Foo.html is processed, a pageview will be generated for it as same as it would be a normal query to your application.

这样,每次处理Foo.html时,都会为它生成一个综合浏览量,就像对应用程序的常规查询一样。

If you'd like to distinguish these Foo.htmls from the normal pageviews, GA has a nice feature called Event Tracking then you should take a look at.

如果您想将这些Foo.htmls与普通网页浏览区分开来,GA有一个很好的功能,称为事件跟踪,那么您应该看看。

#5


1  

I ended up using the WebBrowser component to load the .html file, and thereby trigger the GA tracker. The WebBrowser component executes the embedded JavaScript.

我最终使用WebBrowser组件加载.html文件,从而触发GA跟踪器。 WebBrowser组件执行嵌入式JavaScript。

using (WebBrowser wb = new WebBrowser())
{
    wb.Url = new Uri(@"mytrackingpage.html");
    while (wb.ReadyState != WebBrowserReadyState.Complete)
    {
        Application.DoEvents();
    }
} 

Now all I have to do is to add some errorhandling, get rid of the ugly DoEvents and move the WebBrowser to a separate thread.

现在我所要做的就是添加一些错误处理,摆脱丑陋的DoEvents并将WebBrowser移动到一个单独的线程。

#6


0  

Google has libraries (in alpha) for several different languages for accessing various google APIs, including Analytics -- there's a nice description here -- https://developers.google.com/analytics/devguides/collection/ and the .NET library is https://developers.google.com/api-client-library/dotnet/apis/analytics/v3

谷歌有几种不同语言的图书馆(用alpha版本)来访问各种谷歌API,包括Google Analytics(分析) - 这里有一个很好的描述 - https://developers.google.com/analytics/devguides/collection/和.NET库是https://developers.google.com/api-client-library/dotnet/apis/analytics/v3

Also keep in mind their privacy policy you have to adhere to when using this: https://developers.google.com/analytics/devguides/collection/protocol/policy

另请注意您在使用时必须遵守的隐私权政策:https://developers.google.com/analytics/devguides/collection/protocol/policy

#1


7  

Google Analytics works by making a webrequest through javascript back to Google's server. If you want to do this programmatically, you just have to make this web request yourself. I would use Fiddler or FireBug to capture what the request looks like when you load the page in your browser. Then you can use that same URL in your .Net app.

Google Analytics(分析)的工作原理是通过javascript将网络请求发回Google的服务器。如果您想以编程方式执行此操作,则只需自己制作此Web请求即可。我会使用Fiddler或FireBug来捕获在浏览器中加载页面时请求的样子。然后,您可以在.Net应用中使用相同的URL。

#2


5  

I have recently released a .net library that allows you to natively log a page view with Google Analytics through code. It is released as open source under GNU so all that is required is proper attribution.

我最近发布了一个.net库,允许您通过代码使用Google Analytics本地记录页面视图。它在GNU下作为开源发布,所以所需要的只是正确的归属。

You can get the library here: http://www.diaryofaninja.com/projects/details/ga-dot-net

您可以在这里获取图书馆:http://www.diaryofaninja.com/projects/details/ga-dot-net

example usage of the API:

API的示例用法:

GooglePageView pageView = new GooglePageView("My page title",
                                "www.mydomain.com",
                                "/my-page-url.html");
TrackingRequest request = new RequestFactory().BuildRequest(pageView);
GoogleTracking.FireTrackingEvent(request);

There is also a built in HTTP Handler that allows you to fire tracking events by simply including a tracking pixel on the page:

还有一个内置的HTTP处理程序,允许您通过在页面上包含跟踪像素来触发跟踪事件:

<img src="/tracker.asmx?domain=mydomain.com&pagetitle=My%20Page%20Title&url=/my-page.aspx" />

Alternatively you can use jquery to track links within a page using Google Analytics (zip, jpg, etc) - blogged about it a while ago here:

或者,您可以使用jquery使用Google Analytics(zip,jpg等)跟踪页面中的链接 - 不久之前在此博客:

http://www.diaryofaninja.com/blog/2009/09/17/random-file-zip-and-pdf-tracking-using-jquery-amp-google-analytics

http://www.diaryofaninja.com/blog/2009/09/17/random-file-zip-and-pdf-tracking-using-jquery-amp-google-analytics

#3


3  

private void analyticsmethod4(string trackingId, string pagename)
{
    Random rnd = new Random();

    long timestampFirstRun, timestampLastRun, timestampCurrentRun, numberOfRuns;

    // Get the first run time
    timestampFirstRun = DateTime.Now.Ticks;
    timestampLastRun = DateTime.Now.Ticks-5;
    timestampCurrentRun = 45;
    numberOfRuns = 2;

    // Some values we need
    string domainHash = "123456789"; // This can be calcualted for your domain online
    int uniqueVisitorId = rnd.Next(100000000, 999999999); // Random
    string source = "Shop";
    string medium = "medium123";
    string sessionNumber = "1";
    string campaignNumber = "1";
    string culture = Thread.CurrentThread.CurrentCulture.Name;
    string screenRes = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;


    string statsRequest = "http://www.google-analytics.com/__utm.gif" +
        "?utmwv=4.6.5" +
        "&utmn=" + rnd.Next(100000000, 999999999) +
    //  "&utmhn=hostname.mydomain.com" +
        "&utmcs=-" +
        "&utmsr=" + screenRes +
        "&utmsc=-" +
        "&utmul=" + culture +
        "&utmje=-" +
        "&utmfl=-" +
        "&utmdt=" + pagename +
        "&utmhid=1943799692" +
        "&utmr=0" +
        "&utmp=" + pagename +
        "&utmac=" +trackingId+ // Account number
        "&utmcc=" +
            "__utma%3D" + domainHash + "." + uniqueVisitorId + "." + timestampFirstRun + "." + timestampLastRun + "." + timestampCurrentRun + "." + numberOfRuns +
            "%3B%2B__utmz%3D" + domainHash + "." + timestampCurrentRun + "." + sessionNumber + "." + campaignNumber + ".utmcsr%3D" + source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium + "%7Cutmcct%3D%2Fd31AaOM%3B";


    using (var client = new WebClient())
    {
        client.DownloadData(statsRequest);
        //Stream data = client.OpenRead(statsRequest);
        //StreamReader reader = new StreamReader(data);
        //string s = reader.ReadToEnd();
    }

}

refer this - http://tilr.blogspot.com/2012/10/google-analytics-use-google-analytics.html

请参阅此内容 - http://tilr.blogspot.com/2012/10/google-analytics-use-google-analytics.html

#4


2  

Google Analytics provides two way to track custom actions, events, or whatever you deal with. In your case, the trivial solution is to generate a virtual pageview for the HTML file your application reads in. Call the appropriate JavaScript function:

Google Analytics提供了两种跟踪自定义操作,事件或您处理的内容的方法。在您的情况下,简单的解决方案是为您的应用程序读入的HTML文件生成虚拟页面视图。调用相应的JavaScript函数:

pageTracker._trackPageview("/Foo.html");

This way every time Foo.html is processed, a pageview will be generated for it as same as it would be a normal query to your application.

这样,每次处理Foo.html时,都会为它生成一个综合浏览量,就像对应用程序的常规查询一样。

If you'd like to distinguish these Foo.htmls from the normal pageviews, GA has a nice feature called Event Tracking then you should take a look at.

如果您想将这些Foo.htmls与普通网页浏览区分开来,GA有一个很好的功能,称为事件跟踪,那么您应该看看。

#5


1  

I ended up using the WebBrowser component to load the .html file, and thereby trigger the GA tracker. The WebBrowser component executes the embedded JavaScript.

我最终使用WebBrowser组件加载.html文件,从而触发GA跟踪器。 WebBrowser组件执行嵌入式JavaScript。

using (WebBrowser wb = new WebBrowser())
{
    wb.Url = new Uri(@"mytrackingpage.html");
    while (wb.ReadyState != WebBrowserReadyState.Complete)
    {
        Application.DoEvents();
    }
} 

Now all I have to do is to add some errorhandling, get rid of the ugly DoEvents and move the WebBrowser to a separate thread.

现在我所要做的就是添加一些错误处理,摆脱丑陋的DoEvents并将WebBrowser移动到一个单独的线程。

#6


0  

Google has libraries (in alpha) for several different languages for accessing various google APIs, including Analytics -- there's a nice description here -- https://developers.google.com/analytics/devguides/collection/ and the .NET library is https://developers.google.com/api-client-library/dotnet/apis/analytics/v3

谷歌有几种不同语言的图书馆(用alpha版本)来访问各种谷歌API,包括Google Analytics(分析) - 这里有一个很好的描述 - https://developers.google.com/analytics/devguides/collection/和.NET库是https://developers.google.com/api-client-library/dotnet/apis/analytics/v3

Also keep in mind their privacy policy you have to adhere to when using this: https://developers.google.com/analytics/devguides/collection/protocol/policy

另请注意您在使用时必须遵守的隐私权政策:https://developers.google.com/analytics/devguides/collection/protocol/policy