
How to disable Sitecore Analytics for single sessions
I struggled a bit, when I got the request to combine the cookie agreement with the Sitecore Analytics. Some research lead me to an interesting idea: Adding a processor to the “<startAnalytics>” pipeline of Sitecore, right after the “CheckPreconditions” processor. Our new processor checks if the visitor accepted the cookies, otherwise the start of Analytics will be aborted.
public virtual void Process(PipelineArgs args)
{
Assert.ArgumentNotNull((object)args, "args");
if (HttpContext.Current.Request.Cookies[CookieAgreement] == null)
{
args.AbortPipeline();
}
}
All you must do, is add this new processor in the “<startAnalytics>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<startAnalytics>
<processor
type="Your.Custom.Processor, Your.Assembly"
patch:after="processor[@type='Sitecore.Analytics.Pipelines.StartAnalytics.CheckPreconditions,
Sitecore.Analytics']" />
</startAnalytics>
</pipelines>
</sitecore>
</configuration>
You can also toggle single cookies, just add a check if the Sitecore Analytics toggle cookie is available, otherwise abort the pipeline too. Then in general cookies are enabled, because they are accepted, but the Sitecore Analytics cookie is toggled off.
Of course, the OptOut is needed too. But to delete a cookie from server-side code, you need to use a workaround I found in the msdn. Just overwrite the cookie with a new one with the same name and an expire date in the past.
if (HttpContext.Current.Request.Cookies["SC_ANALYTICS_GLOBAL_COOKIE"] != null)
{
HttpCookie myCookie = new HttpCookie("SC_ANALYTICS_GLOBAL_COOKIE");
myCookie.Expires = DateTime.Now.AddDays(-1d);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
By the way, it is not possible to configure the name of the Sitecore Analytics Cookie (even in 8.2.7, I haven’t checked Sitecore 9). The name is set in the Sitecore.Analytics.Web.ContactKeyCookie.