How to provide custom names for page view events in Azure App Insights?

前端 未结 3 656
说谎
说谎 2021-01-19 14:31

By default App Insights use page title as event name. Having dynamic page names, like \"Order 32424\", creates insane amount of event types.

Documentation on the mat

3条回答
  •  甜味超标
    2021-01-19 15:33

    With help of Dmitry Matveev I've came with the following final code:

    var appInsights = window.appInsights;
    
    if (appInsights && appInsights.queue) {
        function adjustPageName(item) {
            var name = item.name.replace("AppName", "");
    
            if (name.indexOf("Order") !== -1)
                return "Order";
    
            if (name.indexOf("Product") !== -1)
                return "Shop";
    
            // And so on...
    
            return name;
        }
    
        // Add telemetry initializer
        appInsights.queue.push(function () {
            appInsights.context.addTelemetryInitializer(function (envelope) {
                var telemetryItem = envelope.data.baseData;
    
                // To check the telemetry item’s type:
                if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType || envelope.name === Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType) {
    
                    // Do not track admin pages
                    if (telemetryItem.name.indexOf("Admin") !== -1)
                        return false;
    
                    telemetryItem.name = adjustPageName(telemetryItem);
                }
    
            });
        });
    }
    

    Why this code is important? Because App Insights use page titles by default as Name for PageView, so you would have hundreds and thousands of different events, like "Order 123132" which would make further analysis (funnel, flows, events) meaningless.

    Key highlights:

    • var name = item.name.replace("AppName", ""); If you put your App/Product name in title, you probably want to remove it from you event name, because it would just repeat itself everywhere.
    • appInsights && appInsights.queue you should check for appInsights.queue because for some reason it can be not defined and it would cause an error.
    • if (telemetryItem.name.indexOf("Admin") !== -1) return false; returning false will cause event to be not recorded at all. There certain events/pages you most likely do not want to track, like admin part of website.
    • There are two types of events which use page title as event name: PageView and PageViewPerformance. It makes sense to modify both of them.

提交回复
热议问题