Where to put Google Analytics code in an ASP.NET web application

I want to find a place to put my Google Analytics code in my ASP.NET web application. I would like to place it somewhere once and do not need to copy and paste the code into several files. Is there somewhere that I could insert it, that I would only need to turn it on once, and all the pages would be completed? Unfortunately, I do not use MasterPages.

+3
source share
6 answers

You need to either have a base page, or put a custom control on every page where you need a script.

In any of them, you can subscribe to the Init event, and then follow these steps:

protected override void OnInit(EventArgs e)
    {
        var myAnalyticsScript = @"<insert_analytics_script_here>";
        this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "analyticScript", myAnalyticsScript);
    }

, , script , . , , .

+3

, Page . : -)

+3

Google. .

.

class PageWithGoogleAnalytics : Page
{
    //some actual code to add analytics
}

class MyCustomPage : PageWithGoogleAnalytics {}
+1

, , , HttpModule, , HTML ASP.NET, , IIS .

Note. I really do not offer this option, but it may be your only choice.

+1
source

You can put it on the page and then include this page wherever you want to check. But the main page is the best for him.

0
source

--- updated -

Add the following class to your app_code


public class WebsitePageBase : System.Web.UI.Page
{
    public const string analyticsCode = "your script goes here..."
    protected void Page_Load(Object sender, e as EventArgs)
    {
       ClientScript.RegisterStartupScript(Me.GetType(),"__analytics_script",analyticsCode )
    }
}


and when you add a new aspx page, you must inherit from the new base class, so for example, you add default.aspx, your outer class should look like this:


public partial class _default : WebsitePageBase
{

}
-3
source

Source: https://habr.com/ru/post/1770319/


All Articles