banner



How To Set Visitor Counter In Website

Updated: February 1st, 2022.Cookies are a super of import function of the web. Imagine the globe without them: you wouldn't be able to use your Facebook or Twitter. They assistance retain data throughout a user'south visit on a webpage, so naturally, they're an important component of spider web analytics, as well.

Past default, Google Analytics and other analytics tools utilise cookies in order to track users' behavior on your website. Unfortunately, I still see many marketers (working with GTM) suffering over not being able to fire Tags for returning visitors, or later on 4 page views, etc.

But this shouldn't be a trouble since y'all tin can utilise Google Tag Director to set and recollect data from cookies in a fairly easy way. In this blog post, I'll evidence y'all how to easily employ cookies with Google Tag Manager and take your web tracking to the next level.

I remember when I was just starting to learn GTM. It was a giant spring for me when I realized I could fix and read cookies without a developer'southward aid. It added much more flexibility and freedom to my tag management.

What if I demand to fire a specific Pop-upwards if a company originally landed on my website from Adwords AND has already viewed v pages? Non a problem!

P.S. some screenshots in this blog post are using the older version of the GTM Preview fashion just that should not bear on your experience much.

Earlier we go along: this topic is also thoroughly explained in the Intermediate GTM Grade

If you adopt video content over blog posts, so you should definitely consider enrolling in my Intermediate Google Tag Manager Course. In it, I volition uncover many GTM features/tips/tricks that are ofttimes missed by intermediate users. Too, you volition get a proper introduction to some technical topics that will help you go to the side by side level with GTM.

Enroll in Intermediate Google Tag Manager course

Why should you even carp with cookies? Few Examples

By setting and reading cookies with Google Tag Manager you can start creating much-sophisticated triggers, such equally:

  • A visitor has viewed v pages. Let'due south show him a popup with a special offer!
  • A visitor is actually a user in your SaaS (Software equally a service) just is currently browsing without logging in. Nonetheless, he/she still has a cookie with value "registeredUser=true" which can be used as a condition for your trigger.
  • A visitor has landed on your website via an chapter link. With each page view, yous can preserve affiliate ID in visitor's cookie. Here'due south the total guide on how to do that.
  • Do you have a pricing page with price reckoner? Let's attach the computer's results (toll) to that detail visitor. This way you'll see how visitors with different cost ranges are behaving on your site.

Pretty neat, huh?

And then What'southward the Plan?

  1. Offset, someone has to set the cookie. That might be either yous (with help of Google Tag Manager) or a programmer.
  2. Then, you need to create a 1st party cookie variable in GTM. It volition look for a cookie with a item name and brand its value available in the data layer. You volition also be able to see it in Google Tag Manager's Preview and Debug mode.
  3. Create a trigger where status involves the aforementioned 1st party cookie variable.
  4. Fire a tag based on a trigger from bullet point No. three.
  5. Turn a profit.

Gear up cookies with Google Tag Manager

In order to set a cookie, you'll need to create a custom HTML tag. Information technology contains Javascript code which defines cookie's name, expiration time, etc.

<script>  (function(){  var cookieName = "visitorFromAdwords"; // Name of your cookie  var cookieValue = "true"; // Value of your cookie  var expirationTime = 2592000; // I month in seconds  expirationTime = expirationTime * chiliad; // Converts expirationtime to milliseconds  var engagement = new Appointment();   var dateTimeNow = date.getTime();    date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Fourth dimension now + one month)  var date = date.toUTCString(); // Converts milliseconds to UTC time string  document.cookie = cookieName+"="+cookieValue+"; SameSite=None; Secure; expires="+date+"; path=/; domain=." + location.hostname.supersede(/^www\./i, ""); // Sets cookie for all subdomains })(); </script>

In the script above, there are three variables that you should edit:

  • cookieName – y'all should requite information technology a meaningful championship, due east.g. visitorFromAdwords, affiliateID, pageviewCount, etc.
  • cookieValue – In example ofvisitorFromAdwords possible values can betrue orfalse. affiliateID cookie'southward value can be 2385437, and pageviewCount cookie's – 5.
  • expirationTime defines when the cookie expires.2592000is 30 days converted to seconds (xxx days * 24 hours * sixty minutes * lx seconds * chiliad milliseconds). If you want the cookie to expire later the session ends (when the browser window is closed), then remove expires="+date+"; from the finish of the script. Keep in mind, that Google Chrome still runs in the background when you close the browser window, thus the cookie will "alive" longer.

At present, yous demand to decide when you want to set that cookie. Should this "set cookie" script fire when URL contains ?gclid= (meaning that a company landed via Adwords campaign)?

Say, we want to set cookies for those visitors, who have establish our website via Google Adwords. In that instance, we demand to create a trigger with the following settings.

Trigger - Visitor from Adwords

When a person clicks any Google advertising, a destination URL contains ?gclid=XXXXXX. That's the reason backside this trigger'due south condition.

Test The Cookie

After you created custom HTML tag with the cookie-setting script and its trigger, next matter you lot should practice is test the implementation with Preview and Debug way. Make sure that the tag fires ONLY when URL contains ?gclid=. If you're new to Preview and Debug manner, read this comprehensive guide.

Now, allow's check whether a cookie is fix correctly. There are two main means to check cookies – the browser's built-in feature (developer tools) or a plugin.

Personally, I am using Chrome plugin called EditThisCookie (also available for Opera users). This really simple and intuitive extension enables me to quickly check which cookies are currently in use and what information do they contain.

If you haven't already installed, download information technology hither. If you're using a different browser, you'll need to observe something on your own.

Anyhow, let'southward go dorsum to EditThisCookie. One time you have installed this extension, a cookie icon will announced next to the Menu icon (in Chrome).

EditThisCookie icon

Get to the website y'all're currently working on, click EditThisCookie icon and you'll see an expanded listing of all cookies that are currently in apply on that website. Look for a cookie named visitorFromAdwords. This little piece of data will help us do the magic in further chapters of this blog post.

Edit this cookie expanded

Read The Cookie

Now, we need to "teach" Google Tag Manager read the cookie and make information technology bachelor as a variable. Go to your GTM account, open list of Variables, and create a new user-defined variable with the following settings:

cookie variable - visitorFromAdwords

This variable searches for cookies with titlevisitorFromAdwords. If information technology spots i, GTM volition read its value and brand information technology available in theVariables tab of Preview and Debug console.

Cookie variable in Preview and Debug mode

This enables yous to usevisitorFromAdwords variable in any GTM tag or trigger, like in the example below:

trigger with cookie

Instance – Fire a Tag on tertiary Page View

This is one of the nigh popular apply cases of cookies with Google Tag Manager. For your convenience, I take prepared a GTM Recipe with a ready-made script that counts the number of page views and fires a trigger later on iii. Merely if you're eager to understand the details, go along reading.

Allow's Count Page Views

Beginning of all, you'll need to create a custom HTML tag that counts folio views. Every time a page refreshes, this script searches for cookiepageviewCount and increments its value by 1.

<script>function setCookie(proper name, value, expires) {  var cookie = name + "=" + value + "; path=/; domain=." + location.hostname.supplant(/^www\./i, "");   if (typeof expires !== "undefined") {  var at present = new Date();  at present.setTime(now.getTime() + expires * 24 * lx * sixty * chiliad);  cookie += "; expires=" + now.toUTCString();  }   document.cookie = cookie; }  role getCookie(proper name) {  var cookies = document.cookie.split up(";"),  toReturn;   for (var i = 0; i < cookies.length; i++) {  var cookie = cookies[i].trim();  if (cookie.indexOf(name + "=") === 0) {  toReturn = cookie.substring((proper noun + "=").length, cookie.length);  }  }   return toReturn; }  (function() {  var pageviewCount = getCookie("pageviewCount");   if (typeof pageviewCount === "undefined") {  pageviewCount = one;  } else {  pageviewCount++;  }   setCookie("pageviewCount", pageviewCount, 30);  })(); </script>

The cookie (set by this Javascript) expires later 30 days. You lot can easily change its elapsing past editingsetCookie("pageviewCount", pageviewCount, 30).

Set this custom HTML to fire on all pages. Refresh Preview and Debug mode, open up EditThisCookie plugin and check whether the cookie was successfully saved. Now, refresh the page. Cookie's value should increase to 2.

pageviewCount cookie

If you want this cookie to be valid only forthat visitor session, here's a modified script (I've removed all parts which are related to the expiration engagement). Go on in mind, that Chrome handles cookies a flake differently (compared to other browsers). Fifty-fifty if you close the tab or window, Chrome all the same might keep running in the background, therefore session cookies might be even so valid.

<script>function setCookie(name, value) {  var cookie = name + "=" + value + "; path=/; domain=." + location.hostname.replace(/^www\./i, "");   document.cookie = cookie; }  function getCookie(name) {  var cookies = document.cookie.split(";"),  toReturn;   for (var i = 0; i < cookies.length; i++) {  var cookie = cookies[i].trim();  if (cookie.indexOf(proper name + "=") === 0) {  toReturn = cookie.substring((name + "=").length, cookie.length);  }  }   return toReturn; }  (role() {  var pageviewCount = getCookie("pageviewCount");   if (typeof pageviewCount === "undefined") {  pageviewCount = i;  } else {  pageviewCount++;  }   setCookie("pageviewCount", pageviewCount);  })(); </script>

Cookie variable and trigger in Google Tag Manager

Since we take createdpageviewCount cookie, at present information technology'south time to "teach" Google Tag Director read the cookie and make it available as a variable. Get to your GTM account and open a list of Variables. Create a new user-defined variable with the following settings:

pageviewCount cookie variable in google tag manager

Side by side, go to Triggers and create a new Page view trigger with the following settings:

trigger with cookie

This trigger will fire when the cookie'southward value is greater or equal to iii.

That's information technology! Y'all can now assign this trigger to any tag you desire, whether information technology is a pop-upwardly or Google Analytics event tag, or whatever. It's upwardly to your imagination.

Spongebob imagination google tag manager

Delete a Cookie

If you want to delete a particular 1st-party cookie, yous need to set its expiration time to the past date, e.g. 1970 January 1st. Such cookies cannot exist, therefore, they immediately expire.

Here'due south a script that you should use:

<script> (part() {     var proper name = 'yourCookieName'; // REPLACE yourCookieName WITH THE Proper name OF THE COOKIE YOU Want TO DELETE     var path = '';  // If needed, supervene upon this     var domain = ''; // If needed, replace this     document.cookie = proper name + "=" + 		((path) ? "; path=" + path: "") + 		((domain)? "; domain=" + domain: "") + 		";expires=Thu, 01 Jan 1970 00:00:01 GMT";     })(); </script>

In the 3rd line of the lawmaking, changeyourCookieName with the name of a cookie you wish to delete. This lawmaking should also be implemented via GTM Custom HTML tag and fired whenever yous need to delete a cookie (e.g. after a conversion, opt-out or something else).

Also, if your cookie has a specified domain and path, insert the values in the 'path' and 'domain' variables (in the JavaScript code). But you can start past keeping those field (in fourth and 5th lines) empty and see if information technology works.

Few More Ideas

If you notwithstanding don't know how to leverage cookies in your marketing stack, here'south nutrient for idea. I hope these examples will help you break the ice:

  • If you run an affiliate program, y'all already know that visitors come to your site via chapter links (which contain unique chapter ID). Yous can fetch that data from URL, fix it as a cookie and send to Google Analytics equally Custom Dimensions. This way you'll meet how well/terrible affiliate traffic is converting. Too, y'all can identify which chapter partner is driving the most engaged traffic.
  • If a person made a purchase on your site, save this fact every bit a cookie. Then, create a pageview trigger that blocks pop-ups (irrelevant to recent buyers).
  • If you lot run a SaaS business, ask developers to set diverse data well-nigh the user to cookies. Even if the user is logged out, you can still identify him/her visiting your website/web log/etc. and send that data to Google Analytics as custom dimensions. But exist aware of PII limitations.

Not all 1st party cookies tin be read with Google Tag Managing director

In fact, this applies not only to GTM just to customer-side JavaScript in full general. If you're already familiar with cookies, y'all know that all the cookies (set on that page) can be seen by going to your browser's developer tools. I'm using Chrome, therefore, the total path to that function is Chrome'southward Menu > More than Tools > Developer Tools > Application > Cookies.

And so cull your domain. You should see something like this:

Those are the 1st party cookies y'all could potentially use in Google Tag Managing director. Various scripts and other functionality on your site set those cookies to your visitors' browsers. However, not all of them can be accessed by JavaScript in your browser (including GTM).

If a cookie has a checkbox in the HttpOnly column, GTM volition non exist able to admission its value. This ways that a 1st party cookie variable volition returnundefined.

Working with cookies and Google Tag Manager: Terminal Words

So at that place you take it. Turns out it's pretty easy to manage cookies with Google Tag Manager. First, you need to burn a custom HTML tag that sets the cookie with a particular value. Then, you need to create a 1st party cookie variable inside GTM.

This variable's value can be transferred to other tools (such as Google Analytics) or used equally a firing condition within a trigger.

If you're looking for ways how to fire a detail tag after 3 folio views, or for those visitors, who take visited a particular page, then cookies should exist your weapon of pick. Another solution is browser storage (localStorage andsessionStorage), but that's a topic for another time.

Do you know more than tricks on how to use cookies with Google Tag Manager? Permit me know in the comments.

By the way, I've noticed some people asking the question "does Google Tag Director utilise cookies past default?". They are worried near diverse privacy regulations. To answer that, I've published a web log post.

How To Set Visitor Counter In Website,

Source: https://www.analyticsmania.com/post/cookies-with-google-tag-manager/

Posted by: thomasallegs.blogspot.com

0 Response to "How To Set Visitor Counter In Website"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel