Hello Sitecorians,
I have had a couple of clients want to tie in the clicks on their website to their Engagement Analytics report data to understand click tracking behavior of their website visitors. As a universal solution, you can use JavaScript, Handler, Page Events, and the Sitecore API to tie this all together for your clients.
For the tracking you can use the goal or page events.However feel free to mix it up as you see fit with your solution.
Page Events:
Page events are located under the “/sitecore/system/Settings/Analytics/Page Events”.You can create the new page events here.
Triggered page events will appear in Experience profile.If you want to show this in “Experience Analytics report” then , you have to register the page event as goal like below.
Goals :
Goals are located under the “/sitecore/system/Marketing Control Panel/Goals” .We can create the new custom goals under this item.
For this example I have created the page event and goals.You can use any one of them.
Steps:
- Create Httphandler for the register the events or goals.
- Create the common AJAX function to call the handler.
- Call the ajax function with passing the goal or page event ID while clicking the button.
Create the ClientEventTracker HttpHandler like below,
using Newtonsoft.Json; using Sitecore.Analytics; using Sitecore.Analytics.Data; using Sitecore.Diagnostics; using System; using System.Web; using System.Web.SessionState; namespace Sitecore.Scientist.Analytics { /// <summary> /// Summary description for ClientEventTracker /// </summary> public class ClientEventTracker : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/javascript"; TriggerEvent(context); } private static void TriggerEvent(HttpContext context) { try { string jsonData = context.Request["jsonData"]; var clientEventData = JsonConvert.DeserializeObject<ClientEventData>(jsonData); if (clientEventData == null) return; if (string.IsNullOrEmpty(clientEventData.EventName)) { return; } if (!Tracker.Enabled) { return; } if (!Tracker.IsActive || Tracker.Current == null) { Tracker.StartTracking(); // init tracker without tracking the endpoint as a page } if (Tracker.Current == null || Tracker.Current.CurrentPage == null) { return; } if (!string.IsNullOrEmpty(clientEventData.PageEventId)) { var eventData = new PageEventData(clientEventData.EventName, Guid.Parse(clientEventData.PageEventId)) { Text = !string.IsNullOrEmpty(clientEventData.Text) ? clientEventData.Text : string.Empty, DataKey = !string.IsNullOrEmpty(clientEventData.Text) ? clientEventData.Text : string.Empty, Data = !string.IsNullOrEmpty(clientEventData.Data) ? clientEventData.Data : string.Empty, }; Tracker.Current.CurrentPage.Register(eventData); return; } else if (string.IsNullOrEmpty(clientEventData.Text)) { Tracker.Current.CurrentPage.Register(clientEventData.EventName, string.Empty); return; } else { if (string.IsNullOrEmpty(clientEventData.Datakey) || string.IsNullOrEmpty(clientEventData.Data)) { Tracker.Current.CurrentPage.Register(clientEventData.EventName, clientEventData.Text); return; } } } catch (Exception exception) { Log.Error(string.Concat("Sitecore.Scientist.Analytics.ClientEventTracker.TriggerEvent: error in event triggering. requestUrl: ", context.Request.Url.AbsolutePath), exception, typeof(ClientEventTracker)); } } public bool IsReusable { get { return false; } } } public class ClientEventData { public string PageEventId { get; set; } public string EventName { get; set; } public string Data { get; set; } public string Datakey { get; set; } public string Text { get; set; } } }
Now need to create the ClientEventTracker.js like below and refer this script file inside head tag in Layout.cshtml.
var eventTracker = false; function AnalyticsPageEvent(jsonData) { this.jsonData = jsonData; this.trigger = function () { var queryString = ''; if (!this.jsonData) { return; } queryString += '&' + 'jsonData' + '=' + JSON.stringify(this.jsonData); if (queryString != '') { var url = '/sitecore/analytics/ClientEventTracker.ashx' + '?ra=' + eventTracker.randomstring() + queryString; eventTracker.request(url); } }; } function EventTracker() { this.request = function (url) { var script = new ClientEventScript(url, true); script.load(); }; this.randomstring = function () { var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var text = ""; for (var i = 0; i < 32; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }; } function ClientEventScript(src, async) { this.src = src; this.async = async; this.load = function () { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = this.src; script.async = this.async; var ssc = document.getElementsByTagName('script')[0]; ssc.parentNode.insertBefore(script, ssc); }; } eventTracker = new EventTracker();
Finally we have to create the our custom.js file for the button click event trigger AJAX functions.
var Scientist = Scientist || {}; $(document).ready(function () { Scientist.Booking.Init(); }); Scientist.Booking = { Init: function () { $(".booking-button").click(function () { Scientist.Booking.TrackBookingEvent(this); }); }, TrackBookingEvent: function (element) { var dataContainer = $(element); var jsonObject = { PageEventId: dataContainer.data("goal"), EventName: "Hotel Booking", Data: "Booking", Datakey: "HotelName", Text:"Booking button clicked" }; var analyticsEvent = new AnalyticsPageEvent(jsonObject); analyticsEvent.trigger(); } };
I have created the button in my view like below,
So while clicking this button it will make the ajax call to register the goal.Once the session ends , you can see the data in reports.
If you can’t see data,Just wait for session end or abandon the session forcefully.
You can check the details in experience profile as well.
Download the Source code from Github.