Google tag manager script error

Data layer variable name in wrong case: "conversionID", "PageCategory", "pageSubcategory", "visitorId", etc. tag must not be included in a tag mu

Data layer variable name in wrong case: «conversionID», «PageCategory», «pageSubcategory», «visitorId», etc.

<script> tag must not be included in a <flow:ifenabled>

<script> tag must not be included in a <ns:robots>

<script> tag must not be included in a <center>

<script> tag must not be included in a <dl>

<script> tag must not be included in a <footer>

<script> tag must not be included in a <form>

<script> tag must not be included in a <header>

<script> tag must not be included in a <i>

<script> tag must not be included in a <p>

<script> tag must not be included in a <section>

<script> tag must not be included in a <span>

Data layer needs to be above the container snippet

HTTP response code indicates tag failed to fire

Remove the «.» from your dataLayer name dataLayer.2_variables. It may cause issues with tracking.

Remove the «.» from your dataLayer name order.grand_total. It may cause issues with tracking.

Remove the «.» from your dataLayer name order.order_id. It may cause issues with tracking.

Remove the «.» from your dataLayer name order.shipping_charges. It may cause issues with tracking.

Remove the «.» from your dataLayer name order.sub_total_eu. It may cause issues with tracking.

Remove the «.» from your dataLayer name order.tax. It may cause issues with tracking.

Tag is included in an iframe

Non-standard implementation

Invalid or missing account ID

Data layer fields should be quoted

Consolidate your tags with Google Tag Manager.

Code found outside of <body> tag

<script> tag must not be included in a <td>

<script> tag must not be included in a <div>

Data layer variable name in wrong case: «conversionID», «PageCategory», «pageSubcategory», «visitorId», etc.

The Data Layer variable name is case-sensitive. If you try to push a variable or event without the proper casing, the push will not work.

Examples:

  • datalayer.push({"pageTitle": "Home"}); // Won't work
  • datalayer.push({"PageTitle": "Home"}); // Better

This means that the data layer variable has not been correctly set up, and this will hamper the tags fired based on these data layers.

Correct the data layer to the correct case.


<script> tag must not be included in a <flow:ifenabled>

The Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <ns:robots>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <center>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <dl>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <footer>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <form>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <header>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <i>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <p>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <section>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <span>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


Data layer needs to be above the container snippet

Datalayer should be added above the container snippet. Variables pushed to the data layer after the container snippet will not be able to fire tags on page loads with a matching condition.

Variables pushed to the data layer after the container snippet will not be able to fire tags on page loads with a matching condition.

Move the datalayer to above the container snippet


HTTP response code indicates tag failed to fire

This error indicates that even though Google Tag Manager code snippet was detected in the page source, the script itself did not execute. Each time the Google Tag Manager script executes, we expect an HTTP Response carrying the container tag details.

This means that Google Tag Manager code is not correctly implemented, because of which any tags added via Google Tag Manager will not be fired.

Remove the current snippet. Get the snippet again from the Google Tag Manager interface and make sure to paste it immediately after the opening <body> tag.


Remove the «.» from your dataLayer name dataLayer.2_variables. It may cause issues with tracking.

We discourage people from using a «.» in dataLayer key names. Example: dataLayer.push({«one.two»: 3}); Not recommended dataLayer.push({«onetwo»: 3}); Recommended

This may cause issues with tag execution.

Don’t use a «.» in dataLayer key names.


Remove the «.» from your dataLayer name order.grand_total. It may cause issues with tracking.

We discourage people from using a «.» in dataLayer key names. Example: dataLayer.push({«one.two»: 3}); Not recommended dataLayer.push({«onetwo»: 3}); Recommended

This may cause issues with tag execution.

Don’t use a «.» in dataLayer key names.


Remove the «.» from your dataLayer name order.order_id. It may cause issues with tracking.

We discourage people from using a «.» in dataLayer key names. Example: dataLayer.push({«one.two»: 3}); Not recommended dataLayer.push({«onetwo»: 3}); Recommended

This may cause issues with tag execution.

Don’t use a «.» in dataLayer key names.


Remove the «.» from your dataLayer name order.shipping_charges. It may cause issues with tracking.

We discourage people from using a «.» in dataLayer key names. Example: dataLayer.push({«one.two»: 3}); Not recommended dataLayer.push({«onetwo»: 3}); Recommended

This may cause issues with tag execution.

Don’t use a «.» in dataLayer key names.


Remove the «.» from your dataLayer name order.sub_total_eu. It may cause issues with tracking.

We discourage people from using a «.» in dataLayer key names. Example: dataLayer.push({«one.two»: 3}); Not recommended dataLayer.push({«onetwo»: 3}); Recommended

This may cause issues with tag execution.

Don’t use a «.» in dataLayer key names.


Remove the «.» from your dataLayer name order.tax. It may cause issues with tracking.

We discourage people from using a «.» in dataLayer key names. Example: dataLayer.push({«one.two»: 3}); Not recommended dataLayer.push({«onetwo»: 3}); Recommended

This may cause issues with tag execution.

Don’t use a «.» in dataLayer key names.


Tag is included in an iframe

The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

This will prevent certain tags from accurately tracking the parent page because of which tags added via Tag Manager may not fire accurately.

The Google Tag Manager snippet must be placed directly in the page, immediately after the opening <body>tag, that you intend on tracking


Non-standard implementation

We have detected Google Tag Manager web requests, but were not able to find the code snippet on the page.

Using non-standard code implementation on a page may prevent tags from being fired.

Verify that your code snippet is working fine. You can make use of the preview and debug tool to ensure all tags added in Google Tag manager are being fired: https://support.google.com/tagmanager/answer/2695660


Invalid or missing account ID

NOTE: If your container ID (i.e. what’s referenced here as ‘account ID’) is of format GTM-XXXXXXX, where the portion after ‘GTM-’ is longer than 6 characters, you may see this error unnecessarily. This false error will be resolved in a future update. In the meantime, as long as your container ID follows the correct format as described below, you may ignore this error.

The account ID added in the Tag Manager snippet is wrong. An example snippet will look something like this:

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXX');</script>
<!-- End Google Tag Manager -->

The «GTM-XXXXX» should be replaced by your account ID. The best way to fix this is to re-install the entire container snippet using the latest guidance. You can find your account-specific snippet in your Tag Manager account:

  1. Log in to your Tag Manager account at https://tagmanager.google.com.
  2. Near the top of your workspace’s home screen, you will see your Google Tag Manager container ID number (formatted as «GTM-XXXXX»). Click it to launch the Install Tag Manager box.
  3. Copy and paste the code snippets into your website as instructed. The <script> portion of the JavaScript snippet will be placed in the <head> of your web page’s HTML output, and the <noscript> section should appear immediately after the opening <body> element. For best results, the <script> portion of the snippet should be placed as close to the opening <head> element as possible, but below any dataLayer declarations. See the Tag Manager developer site for further installation details.

Data layer fields should be quoted

While quotes are not strictly required for variable names that consist of only letters, numbers, and underscores, and which are not reserved words (e.g. function, export, native, etc.), to avoid issues, it»s recommended that all variable names be enclosed in quotes. Examples: dataLayer.push({new-variable: «value»}); // Won»t work dataLayer.push({«new-variable»: «value»}); // Better


Consolidate your tags with Google Tag Manager.

Google Tag Manager allows you to conveniently manage tags (such as tracking and marketing optimization tags) on your site. You can add and update AdWords, Google Analytics, Floodlight, and non-Google tags from the Google Tag Manager user interface instead of editing site code. This reduces errors, frees you from having to involve a webmaster, and allows you to quickly deploy tags on your site.

To manage your tags using Google Tag Manager, you’ll need to: go to google.com/tagmanager to create a Google Tag Manager account (or to access an existing account). create a container for your site in the account, add the container snippet to your site, while removing any existing tags on your site. You’ll then be ready to add tags to your site via the Google Tag Manager user interface. For more information, read Setup and Workflow.


Code found outside of <body> tag

NOTE: Please ignore this error. The recommendations for how to implement the Google Tag Manager container code have changed. While implementations with the container code entirely in the <body> will continue to work as is, it’s now recommended that the container code be split, with the <script> portion in the <head> and the <noscript> portion in the <body>. Further context may be found in this blog post. This false error will be resolved in a future update. In the meantime, you may ignore this error.


<script> tag must not be included in a <td>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


<script> tag must not be included in a <div>

Google Tag Manager Tag should be placed immediately after the opening <body> tag and not inside any other HTML element. The Google Tag Manager snippet must be placed directly in the page that you intend on tracking. Placing it in a hidden iframe or deploying it within another tag management system will prevent certain tags from accurately tracking the parent page.

Tags added via Google Tag Manager may not fire.

Please make sure to place the Tag Manager snippet immediately after the opening <body> tag.


Содержание

  1. #GTMTips: Track JavaScript Errors As Events
  2. Tip 43: Track JavaScript Errors As Events
  3. 1. Track errors as Google Analytics Goals
  4. 2. Use Environments or the Debug Mode
  5. 3. Add manual sampling
  6. 4. Script Error
  7. Summary
  8. Устранение неполадок
  9. Tracking Errors with Google Tag Manager: 5 Things to Measure
  10. Table of Contents
  11. #1. Track JavaScript Errors with Google Tag Manager
  12. #1.1. How to Configure JavaScript Error Trigger in Google Tag Manager
  13. #1.2. Why is it useful?
  14. #2. Track 404 Errors with Google Tag Manager
  15. #2.1. Hit-scoped custom dimension – Referrer
  16. #2.1.1. Custom Dimension in GA
  17. #2.1.2. GA Settings Variable
  18. #2.2. Ask a developer to push the 404 error to the Data Layer
  19. #3. Checkout Errors
  20. #4. Form Errors (e.g. Registration and Login forms)
  21. #4.1. Using Element Visibility trigger to track form errors
  22. #4.2. Working with an AJAX form? Try this
  23. #4.2.1. Data Layer Variables
  24. #4.2.2. Trigger (when the error message is pushed to the Data layer)
  25. #4.2.2. Google Analytics tag
  26. #5. Server Error (like 50x, etc.)
  27. #5.1. Lookup Table Variable
  28. #5.2. Trigger
  29. #5.3. Tag
  30. Checking Error Data in Google Analytics
  31. Several Tips Regarding Error Naming Convention
  32. Treating Errors as Negative Goals in Google Analytics
  33. GA Custom Alerts
  34. Final words

#GTMTips: Track JavaScript Errors As Events

Back back to the friggin’ basics. Almost two years ago, I wrote a two-parter on how to have fun with Google Tag Manager: Part 1, and Part 2. The first part had a nice exercise for tracking JavaScript Errors as Google Analytics Events, using the recently published “JavaScript Error Listener” Tag.

Well, that was in GTM V1. Now we’ve been smoothly sailing with the wonderful new interface for well over a year, and it’s time to update some of these nifty tricks. In this #GTMTips post, I’ll show you how to track uncaught JavaScript errors in the new interface, plus give you some tips on the overall process.

The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!

Tip 43: Track JavaScript Errors As Events

The process is actually really simple. Much easier than it was in the previous Google Tag Manager interface.

By the way, uncaught refers to an error which hasn’t been captured and handled by any of the scripts on the page. The most common way to catch an error is to use try. catch blocks around your code, which capture any errors which bubble up to the context where you have the block. If an error makes its way through without having been caught in any way, it will trigger the JavaScript Error Trigger. Thus it’s a good way to audit your current error detection methods, too!

Anyway, you start by making sure the Built-In Variables are activated.

If you’re curious about these Built-In Variables, check the relevant section of my Variable Guide For Google Tag Manager.

Next, head on over to Triggers, and create a new one:

I’m going to let the Trigger fire on “All JavaScript Errors”, but be sure to read to the end of this post for tips regarding this selection.

Finally, you need a Google Analytics Event Tag, which collects and concatenates all this information. Here’s what I use:

An example result using these settings would be something like:

Event Category: JavaScript Error
Event Action: Uncaught ReferenceError: appear is not defined
Event Label: 1255: https://www.simoahava.com/scripts/bundle.js

I’m sending the event as Non-Interaction: True, because it’s not a user interaction, and I don’t want it to be counted as such.

And that’s it for the implementation!

Now, there are some things you might want to consider when implementing this on your own website. The next chapter will tackle these issues.

Tracking JavaScript Errors can be quite the bipolar experience. On the one hand, it’s just a good, solid developer attitude to want to know about what’s breaking up or already broken on your site. On the other hand, it can cause a deluge of Events in your Google Analytics profile, leading to sessions reaching their hit limits and severe sampling issues. So here are a couple of tips to manage it all.

1. Track errors as Google Analytics Goals

“Track ERRORS as GOALS, what has he been smoking?!” I hear you exclaim. Yeah, it’s not a business goal, but goals can also be negative goals. The reason I’m interested in this particular negative goal, is because I want to see a Conversion Rate for sessions with JavaScript Errors. This will allow me to do all sorts of cool analyses on how the error rates are fluctuating over time. To set up the goal, you can use the following settings:

Next, you can create an Alert, which sends you an email every time the number of JavaScript Errors has gone up significantly on your site:

Now you’ll get an email every time there’s a significant increase in the number of JavaScript Errors recorded on your site.

2. Use Environments or the Debug Mode

Tracking every single uncaught JavaScript error can lead to a deluge of hits. The modern website is best known for the number of errors it dispatches, not the fancy UI or the awesome new framework it utilizes. To keep the number of errors down, you might want to delimit them to only fire in a specific environment, or when in the Debug Mode. You could, for example, allow the Error Trigger to work only in the staging environment.

This way only errors triggered by your testers and developers will be recorded. The downside, of course, is that it’s not an authentic setting, and no matter how much you test and debug, you will always miss some things.

3. Add manual sampling

Another way to prevent every single error from dispatching is to manually sample the hits that are sent to Google Analytics. You could, for example, only let the Trigger fire for 50% of recorded errors. You can use the Random Number Built-In Variable here:

The trick is to only fire the Trigger when the Random Number Variable returns a number that ends in 0, 1, 2, 3 or 4. That’s 50% of the possible numbers it can end in.

Naturally, the downside here is that you might miss some outlier errors, which only pop up every now and then. But you should still catch most of the significant ones.

4. Script Error

If your site is using JavaScript files loaded from external content distribution networks, the messages and line numbers of the errors dispatched in these external scripts are not exposed in the browser. This is a reality you’ll have to work with. There’s no way to identify where and what error took place, as the browser will only dispatch the nondescript “Script Error.” message with a line number of 0. The URL of the script is still exposed, though, and you can use that to narrow down the possible errors.

It’s a good idea to host as many scripts as possible on your own website. Not only will you know more about the errors that are thrown, but also being subservient to an external CDN can introduce security issues, if the third party decides to add some malicious or dangerous code to the library you’re using (or if they’re hacked).

Summary

I hope this tip has been useful. Tracking errors is one of the ways to make sure that your website is catering an optimized experience for your visitors. Google Analytics provides a great tool for tracking these errors, because it also lets you create session- and user-scoped segments around error events. With those segments, you can start analyzing the actual business impact of errors thrown on the site.

An error in the eCommerce checkout funnel can be destructive to your business, and using Google Analytics for detection can help you get on top of things before you’ve lost too much money.

Источник

Устранение неполадок

При каждой загрузке страницы с фрагментом-контейнером Google Менеджера тегов запрашивается событие gtm.js JavaScript. Все запросы GIF и другие действия, реализуемые через Менеджер тегов согласно заданным правилам, выполняются после этого запроса. Проверить, правильно ли запускаются теги, можно с помощью инструментов отладки. В таблице ниже перечислены инструменты, предназначенные для наиболее популярных браузеров.

Браузер Инструмент
Все Firebug Lite
Все Charles
Все (на базе Windows) Fiddler
Chrome Встроенные инструменты разработчика (например, раздел Resources)
Firefox Live HTTP Headers
Firefox Firebug
Safari Встроенное окно «Активность»

Установив и настроив инструмент, откройте веб-страницу, которую вы хотите проверить, и проанализируйте отчет о трафике. Сначала необходимо убедиться в том, что страница действительно запрашивает событие gtm.js JavaScript (а указанный идентификатор соответствует идентификатору Google Менеджера тегов). Если вы видите этот запрос, значит контейнер Google Менеджера тегов реализован. Затем проверьте, происходит ли на странице активация тегов. Если согласно отчету теги не активируются, убедитесь в следующем:

  1. Ваш фрагмент-контейнер реализован в соответствии с Кратким руководством по началу работы.
  2. Идентификатор, указанный в контейнере, совпадает с идентификатором вашего контейнера в Google Менеджере тегов.
  3. Все изменения, внесенные вами в правила и теги, сохранены и отображаются в Менеджере.
  4. В правилах соблюдаются типы соответствия.
  5. Страница не загружена из кеша (выполнен обход кеша).

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Источник

Tracking Errors with Google Tag Manager: 5 Things to Measure

There are lots of cool things you can do with Google Tag Manager, like track purchases, form submissions, link clicks, etc. All of these are positive actions for the business. But what about negative ones? Errors should be definitely tracked as well as they might provide you with some gems.

In fact, identifying where your visitors/customers are struggling and fixing those issues can be a fast-track to improved conversions.

So what kind of errors can you track with GTM? In this guide, we’ll take a look at 5 different groups of errors that you can track with Google Tag Manager.

Note: this blog post teaches how to track events with Universal Analytics. If you want to get familiar with event tracking in Google Analytics 4, you can also refer to this blog post.

Table of Contents

Errors are listed in no particular order, therefore, don’t think that error #5 is less valuable than #1.

#1. Track JavaScript Errors with Google Tag Manager

GTM has a built-in trigger that captures uncaught JavaScript errors. If you take a look at the list of all possible trigger types in GTM, you can probably easily guess which trigger I’ll be talking about. Yes, it’s a JavaScript Error trigger.

#1.1. How to Configure JavaScript Error Trigger in Google Tag Manager

Uncaught means that an error wasn’t captured and handled by some script on a page. In plain English: if an unexpected error occurs in JavaScript code and that code was not programmed to deal with it in some way, JavaScript Error trigger will track it.

Important: you should not think that this trigger catches ALL possible errors on a page. If a JS error occurs on a page and the script was programmed to handle it by showing a certain error/warning popup to a visitor, such error will not be tracked by GTM.

To get started, go to Triggers > New > Trigger Configuration > JavaScript Error. Leave all the settings as they are and save the trigger.

Also, go to Variables > Configure (in the Built-in Variables section) and enable Error Message, Error URL, Error Line.

When GTM captures an error, you can get 3 data points with it:

  • Error message (the text of the JavaScript error message, for example, Uncaught ReferrerceError: testvariable is not defined )
  • Error URL (the address of the page where the error occurred)
  • Error Line (the line number in the code where the error was detected)

You could send all of those data points to Google Analytics. To do that, go to Tags > New > Universal Analytics and enter the following settings (make sure that you have already enabled the Error Variables in the container):

Note: set the field Non-interaction hit to true. This means that GA will not treat this event as an interaction and the errors that you catch will not affect your bounce rate.

Finally, assign the JavaScript error trigger (that you have previously created) to this Universal Analytics tag. Save the tag, refresh/enable the preview mode.

If you want to test this, you can add this code (temporarily!) to a page via content management system:

When you save the page and refresh it (but before that, refresh or enable the GTM preview and debug mode), you should see the JavaScript error in the GTM debug console.

Remember, the aforementioned line of code intentionally contains a JS error. Remove it immediately after the test is done.

#1.2. Why is it useful?

If your developer is not tracking JavaScript errors with a dedicated tool (like TrackJS), JavaScript Error tracking with Google Tag Manager is definitely better than nothing (of course, you should not think this is 100% accurate).

You can track JS errors as negative goals and then see the number of sessions that had at least one error (more on negative goals — later in the blog post).

Another idea: Sequence segments. For example, show all the sessions that entered the checkout and then had a JavaScript error but did not make a purchase.

This segment is more useful for those businesses where customers are usually converting in the same session they arrive.

These are just several ideas and everything depends on your imagination.

#2. Track 404 Errors with Google Tag Manager

Another type of error that you can track with Google Tag Manager is 404, a.k.a. Page Not Found. I have a separate blog post (covering other alternatives too) for that but here are some of the highlights + new ideas.

There are several different ways how to tackle 404 error tracking. I’ll mention two:

  1. Sending a hit-scoped custom dimension to GA (Referrer) and then using it as the secondary dimension in GA reports. This works if “Page not found” error can be distinguished by the page title
  2. Asking a developer to push the 404 event to the Data Layer

#2.1. Hit-scoped custom dimension – Referrer

This method will be useful if the page title of 404 pages contains “Page not found”, “Page missing” or some other phrase that lets you easily identify that a visitor has landed on a 404 page.

How can you check that? Open a website you’re working on, and add some gibberish at the end of the URL, e.g. https://www.youwebsite.com/posts/somenonsense

Are you redirected to a 404 page? What is the title of the page? (you can check that in the browser tab):

So if you indeed see something meaningful (and related to “page not found”) here, continue reading. By the way, huge thanks to Charles Meaden who mentioned this idea in one of my previous blog posts about the Referrer Variable in Google Tag Manager.

#2.1.1. Custom Dimension in GA

In your Google Analytics, you will need to create a custom dimension. Go to Admin (click the gear icon in the bottom left corner of the GA interface) > Property column (make sure you have selected the needed property) > Custom Definitions > Custom Dimension > New Custom Dimension.

Enter the following settings:

  • Name: CD – Referrer (or you can call it just “Referrer”, it’s up to you which Naming Convention to use)
  • Scope: Hit

Once you do that, you will see the number (index) of the custom dimension. Remember it. We’ll need it quite soon.

#2.1.2. GA Settings Variable

I really hope that you already are using this variable in your GA/GTM setups. If you don’t, read this guide. If you do, then do the following:

  • In the variable (that is used by your Universal Analytics tags), click More Settings > Custom Dimensions
  • Enter the index number of your Custom Dimension (for example “5” without quotation marks) in the left column and <> the right one (this variable is enabled in the GTM container by default).

Once this is done, together with every hit (event, pageview, etc.) you will be sending the value of Referrer. In a nutshell, this variable passes the web address of the previous page.

This is useful because you can then better understand where are people coming from to that 404 page and, therefore, will be able to fix the issue sooner.

How can you see that data in GA reports? Go to Behavior > Site Content > All Pages.

Change the primary dimension to Page Title

And then add the CD – Referrer (or whatever you named it) as a secondary dimension.

Finally, in the search field enter “Page not found” (or whatever your website uses as a title of the 404 page).

Voilà! You now have a report of “Page not found” and you also see the previous page that a visitor was on (meaning that those previous pages probably contain broken/outdated links).

Important: this Custom Dimension will NOT affect your past data. Only new hits to GA will be sent together with a “Referrer” custom dimension.

Also, you can create custom GA reports with more dimensions (columns) at the same time:

#2.2. Ask a developer to push the 404 error to the Data Layer

If the previous option did not work for you, here’s another one. Whenever a visitor lands on a page that contains a 404 (page not found) error, ask a developer to activate the following code (preferably, before the GTM container snippet):

P.S. You are free to use different values for those keys that match your own naming convention.

This code will push the error information to the Data Layer.

Once a developer implements the code, you will need to:

  1. Create a Custom Event Trigger
  2. Create a Data Layer Variable
  3. Create a Google Analytics Event tag that sends the 404 error to GA as an event (non-interaction)

First, let’s start with a trigger. Go to Triggers > New > Custom Event Trigger and enter the following settings:

Enter the value of the “event” key in the “Event name” field. If you used my code example, then enter “error” (without quotation marks).

Then, the Data Layer Variable. Go to Variables > User-defined Variables > New > Data Layer Variable. Enter the following settings if you have precisely copied my code example:

Important: event names are case-sensitive in GTM.

Last but not least, Universal Analytics (GA) tag. Go to Tags > New > Universal Analytics and enter the following settings:

This should also be configured as “Non-interaction hit: true”.

Don’t forget to test the setup with the GTM preview and debug mode + publish the changes after that.

#3. Checkout Errors

The third group of errors that should definitely get your attention is checkout errors. I’d say that these are one of the most important ones because the visitor/user is very close to the conversion (e.g. purchase, signup, etc.).

Your goal is to reduce friction/struggle as much as possible.

What kind of errors should you track? Consult with a developer of that checkout what is possible.

Here are some ideas:

  • Form-related errors (like “some required fields are not filled in: first name, address”)
  • Form-field-related errors (like “invalid shipping address”)
  • Payment-related errors (like “insufficient funds” or “card declined”) (just make sure things like credit card data is not tracked)

After identifying groups of errors that you want to track, ask a developer to push those errors to the Data Layer, here’s a sample code:

Then apply the same principle I’ve explained in chapter #2.2. of this blog post, create:

  • Custom event trigger
  • Data Layer variables (for errorType and errorMessage)
  • Google Analytics tag

Here’s what the tag should look like (don’t forget to assign the Custom Event trigger to this tag)

If you have already implemented the 404 tracking with the developer’s help, then you will already have one variable and the trigger. No need to create duplicates for that.

#4. Form Errors (e.g. Registration and Login forms)

There are different ways how to track form errors. Some are more reliable, the others are less. The most robust way is, once again, to cooperate with a developer and ask him/her to push the error data to the Data Layer.

I will not explain this principle all over again. Please revisit chapter #2.2. of this blog post.

In addition to the “Developer + Data Layer” method, here are some other alternatives. Remember, they might be more fragile and cause more significant data inaccuracies:

  1. Track when the error message of the form appears on the screen
  2. Using AJAX form? Check the response when the form is submitted (maybe you’ll find something useful there)

#4.1. Using Element Visibility trigger to track form errors

Warning: for this method to work, you will probably need to become familiar with CSS selectors, which is an advanced topic.

So if you have a form that displays an error message (after the form was submitted with an error), here’s what you could do.

First of all, do the right-click on that error message and see what kind of classes or IDs does it have. Once again, I cannot stress this enough: this method will work if you have the right CSS Selector fundamentals in your head.

Here’s an example of what I see after I start inspecting a certain element (P.S. this does not mean that you will see the same thing (because the majority of websites are unique)).

Take a closer look at the class attribute of that error message. One of the classes is wpcf7-validation-errors. We could use that in our GTM trigger.

Go to Triggers > New > Trigger Configuration > Element Visibility and enter the following settings:

In CSS, all classes start with a dot. That’s exactly what we did: we entered .wpcf7-validation-errors. Also, make sure you enable the “Observe DOM changes” setting.

Let’s test whether the trigger works properly. Save the trigger, refresh/enable the GTM Preview and Debug mode, refresh the page with the form and submit the form with one required field missing (or some other error you know).

You should see the Element Visibility event appear on the left side of the Preview mode panel.

Now, how can you access the text of that error message? The neat trick is that Click Text or Form Text, built-in variables in GTM, return the text of the element that was tracked by the Element Visibility trigger. Learn more about this here.

Now, it’s time for a tag. Go to Tags > New > Universal Analytics and enter the following settings:

I recommend tracking all page errors under the same category “error” (with some exception). I’ll explain my naming convention a bit later in this blog post.

As always, error events in GA should be tracked as Non-interaction hit: true.

Where will you see this event in GA?

  • Realtime > Events (for debugging). If you don’t see the event, read this guide.
  • Behavior > Events > Top Events (keep in mind that the events will not appear here in real-time. You’ll need to wait. Also, don’t forget to include today’s data by adding it in the GA date-picker).

#4.2. Working with an AJAX form? Try this

If your form does not reload the page after it was submitted (or when the error is displayed), there is a chance that the form was built by using the AJAX.

How can you make sure you’re working with an AJAX form? Click this link (credit for this code goes to Bounteous), copy the entire code and paste it into a new Custom HTML tag within your GTM container. Set the tag to fire on All Pages. Save the container, refresh the preview mode and refresh the page where the form is located.

Custom HTML tag will fire on a Pageview event. Don’t worry about that. Now try to submit the form properly. Did the ajaxComplete event appear in the GTM preview mode? Yes? This means you’re working with an AJAX form.

Now try to submit a form with at least one empty required field. Did the ajaxComplete event appear again? If yes, click that event in the preview mode and go to the Data Layer tab.

Scroll down and keep looking for the response section.

Do you see something meaningful there that is related to an error? In my case, I see this (Warning: the data structure of the response might look totally different in your case):

It would be cool to access that status and message values, right? Luckily, we can do that.

#4.2.1. Data Layer Variables

Go to Google Tag Manager > Variables > User-defined Variables > New > Data Layer Variable.

In my example, the status key is in the object response that is in another object called attributes. That is why in the Data Layer Variable, you should enter attributes.response.status (if you have no clue what I’m doing here, read this guide)

Save the variable. Now, it’s time to access the message. Enter attributes.response.message in the Data Layer Variable.

Save the variable.

#4.2.2. Trigger (when the error message is pushed to the Data layer)

Now, it’s time to create a trigger that will be activated when an ajaxComplete will be pushed to the Data Layer and attributes.response.status will equal to validation_failed.

Save the trigger

#4.2.2. Google Analytics tag

And the last step — Universal Analytics tag. Go to Tags > New > Universal Analytics and enter the following settings.

I’ve inserted the attributes.response.message as the Event Label. Every time an AJAX form error will be pushed to the Data Layer, I will pass its text/message to Google Analytics.

Important: If you have named your variables differently (e.g., not dlv – attributes.response.message), then use your naming in the GA tag, not mine.

Save the tag, refresh the preview mode, refresh the page with that form and submit it with an error. Check if the ajaxComplete event was fired and whether it is visible in the GA real-time reports. As for the Standard GA reports, these events will (as usual) appear in the Behavior > Events > Top events report.

#5. Server Error (like 50x, etc.)

When a server error occurs on a page (e.g. “Internal server error” or “Bad Gateway”, etc.), they look like this (pardon me or an old screenshot I found online):

Simple plain text page. However, GTM (or any other snippets) on that page is not available, thus you cannot track them by default. As a solution (I honestly don’t know whether this is the only workaround), you could ask a developer to redirect visitors to a static error page (each error will probably have a unique error page (visually similar but with a different error message)).

For example, if 500 error occurs, a developer could redirect a visitor to a yourwebsite.com/500error.html (or something like that). If 503, then yourwebsite.com/503error.html.

My examples here totally made up. The URLs of your error pages might look totally different. However, keep in mind that only a developer can implement these redirects to error pages.

All error pages could use the same HTML file template with some basic error information and the Google Tag Manager container snippet. The snippet is the key here. Without it, no error tracking will be possible. Some companies even go the extra mile with a custom error page design that might look like this:

If URLs of the error pages contain the error code (e.g. yourwebsite.com/500error.html), you can implement the same method that I’ve explained in #2.1 chapter of this article.

If, however, the URLs aren’t very friendly, e.g., yourwebsite.com/error1.html means 500 error, then you could implement something like this. Create a Lookup Table or Regex Table variable that will check the Page Path and will return a more meaningful/readable value.

#5.1. Lookup Table Variable

For this example, I will use a Lookup Table variable (that will be looking for exact matches).

A hypothetical situation. Our website has 5 error pages for different types of server errors:

  • mywebsite.com/error1.html is for error 500 (if you are not familiar with error codes, here they are)
  • mywebsite.com/error2.html is for 502
  • mywebsite.com/error3.html is for 503, etc.

Here what we could do. In GTM, go to Variables > User-defined Variables > New > Lookup Table. Choose <> as an input variable. Then create separate rows for each error page.

Since we will be working with a <>, we will need to enter what comes after the slash in the URL, e.g. error.html. Let’s do that:

Then, on the right side of each column enter the output that you want to use (in other words, we will turn the ambiguous error.html into 500 error).

If in the future, you plan to implement more error page templates, it’s a good practice to set the “default” value of the table variable. If none of the conditions/rows are met, this variable will default to the <>.

Save the variable.

#5.2. Trigger

Now, let’s create a trigger that will be activated when the visitor loads an error page. Go to Triggers > New >Trigger Configuration > Pageview and enter the following condition:

In our case, Page Path or an error page starts with “error” and ends with “.html”.

#5.3. Tag

Finally, let’s create a Google Analytics event tag that will send the error to GA. Go to Tags > New > Universal Analytics and enter the following settings.

With the help of the Lookup Table variable, you will be sending the actual error codes to GA.

Assign the pageview trigger to this tag, save it. Don’t forget to test and then publish your changes.

Checking Error Data in Google Analytics

Now, it’s time to check your error data in Google Analytics. If you were tracking them as events, you will find them in Behavior > Events > Top Events report. If you followed my naming convention, error Event Category is the one that you should be looking for.

Just keep in mind that:

  • This data does not appear immediately. You will still need to wait (sometimes 15 minutes, sometimes hours. Start panicking after 24 hours.).
  • By default, GA standard reports do not include today’s data. So don’t forget to include it in the date picker.

If some of the errors are tracked as pageviews (e.g. like in #2.1. chapter), then you will find that data in Behavior > Site Content > All Pages. Switch to Page Title primary dimension and then add any secondary dimension if you need it.

Several Tips Regarding Error Naming Convention

This is NOT some hard rule that you MUST follow. It’s up to you how will you name your events in GA. But my personal preference is to group all errors under the Event Category error. JavaScript errors can be an exception and I can treat them as a separate event category (because there is more information that you can get from the JS error trigger). So, it’s up to you to decide.

Then the Event Action would be the type of an error, e.g.:

  • checkout error
  • server error
  • 404 error
  • form error (for general landing page opt-ins)
  • registration error
  • login error, etc.

Event Label should be used for the description of the error. What exactly was the error? For example:

  • If the error is in the checkout, an error message/text would be valuable (like “credit card declined”)
  • If the error was server-side, then the error code (e.g. 503) and the location (URL) would be nice (or at least the error code)
  • If the error is related to a form, then I’d like to know the error text

You get the idea. But once again, these are just my thoughts. You are free to choose a different naming convention.

Treating Errors as Negative Goals in Google Analytics

Usually, goals are treated as positive (for a business) interactions that a visitor/user completed on a site. But it does not always have to be that way. It also makes sense to track a negative conversion rate (shout out to Mikko who was spreading this message in 2019).

What is the percentage of your sessions where visitors/users/customers had at least one error in the checkout? 20%? I think you should take a closer look at that.

If you want to treat every error (that is event-based) that was tracked on a page (and if you followed my naming convention), you could just go to GA Admin (in the bottom left corner) > View column > Goals and create a goal with the following settings:

  • Custom template
  • Name – anything you want
  • Type – Event
  • Event conditions:

This will treat any event of which Event Category equals to error.

If you want to be more specific and track only, say, checkout errors as negative goals, you can enter goal settings similar to these ones:

Once you set the goal, you can find them in multiple reports within Google Analytics, for example, Acquisition > All Traffic > Source/Medium

Or Conversions > Goals > Overview

GA Custom Alerts

I will not dive deeper into how to configure them. Instead, you can read this guide. But I still wanted to mention that such functionality exists. You can configure GA to send you email notifications if the number of certain errors on a page reaches a certain threshold.

Rule of thumb: set alerts only for the most essential problems like server errors or checkout. I would not personally monitor JavaScript errors with an alert because in many cases, users might not even notice that such error has occurred.

If your thresholds for alerts are too low, you will be overwhelmed by the number of notifications and eventually, will start ignoring them. It takes some time to find the proper (not too high but not too low either) threshold.

Final words

These were some of the ideas about Error Tracking with Google Tag Manager. Every business is different, therefore, types of errors that you can/will measure will also be different.

Personally, I always try to track:

  • Form-related errors
  • Checkout errors
  • Registration errors
  • 404 errors

The first three are directly related either to revenue or lead acquisition (that may eventually lead to revenue increase). 404 errors are quite easy to track and may help you identify missed opportunities when a visitor lands on your page, finds nothing and bounces.

Got something to add? Use the comments section below!

Источник

There are lots of cool things you can do with Google Tag Manager, like track purchases, form submissions, link clicks, etc. All of these are positive actions for the business. But what about negative ones? Errors should be definitely tracked as well as they might provide you with some gems.

In fact, identifying where your visitors/customers are struggling and fixing those issues can be a fast-track to improved conversions.

So what kind of errors can you track with GTM? In this guide, we’ll take a look at 5 different groups of errors that you can track with Google Tag Manager.

Note: this blog post teaches how to track events with Universal Analytics. If you want to get familiar with event tracking in Google Analytics 4, you can also refer to this blog post.

Table of Contents

  • #1. Track JavaScript Errors with Google Tag Manager
    • #1.1. How to Configure JavaScript Error Trigger in Google Tag Manager
    • #1.2. Why is it useful?
  • #2. Track 404 Errors with Google Tag Manager
    • #2.1. Hit-scoped custom dimension – Referrer
      • #2.1.1. Custom Dimension in GA
      • #2.1.2. GA Settings Variable
    • #2.2. Ask a developer to push the 404 error to the Data Layer
  • #3. Checkout Errors
  • #4. Form Errors (e.g. Registration and Login forms)
    • #4.1. Using Element Visibility trigger to track form errors
    • #4.2. Working with an AJAX form? Try this
      • #4.2.1. Data Layer Variables
      • #4.2.2. Trigger (when the error message is pushed to the Data layer)
      • #4.2.2. Google Analytics tag
  • #5. Server Error (like 50x, etc.)
    • #5.1. Lookup Table Variable
    • #5.2. Trigger
    • #5.3. Tag
  • Checking Error Data in Google Analytics
  • Several Tips Regarding Error Naming Convention
  • Treating Errors as Negative Goals in Google Analytics
  • GA Custom Alerts
  • Final words

Errors are listed in no particular order, therefore, don’t think that error #5 is less valuable than #1.

#1. Track JavaScript Errors with Google Tag Manager

GTM has a built-in trigger that captures uncaught JavaScript errors. If you take a look at the list of all possible trigger types in GTM, you can probably easily guess which trigger I’ll be talking about. Yes, it’s a JavaScript Error trigger.

#1.1. How to Configure JavaScript Error Trigger in Google Tag Manager

Uncaught means that an error wasn’t captured and handled by some script on a page. In plain English: if an unexpected error occurs in JavaScript code and that code was not programmed to deal with it in some way, JavaScript Error trigger will track it.

Important: you should not think that this trigger catches ALL possible errors on a page. If a JS error occurs on a page and the script was programmed to handle it by showing a certain error/warning popup to a visitor, such error will not be tracked by GTM.

To get started, go to Triggers > New > Trigger Configuration > JavaScript Error. Leave all the settings as they are and save the trigger.

Also, go to Variables > Configure (in the Built-in Variables section) and enable Error Message, Error URL, Error Line.

When GTM captures an error, you can get 3 data points with it:

  • Error message (the text of the JavaScript error message, for example, Uncaught ReferrerceError: testvariable is not defined )
  • Error URL (the address of the page where the error occurred)
  • Error Line (the line number in the code where the error was detected)

You could send all of those data points to Google Analytics. To do that, go to Tags > New > Universal Analytics and enter the following settings (make sure that you have already enabled the Error Variables in the container):

Note: set the field Non-interaction hit to true. This means that GA will not treat this event as an interaction and the errors that you catch will not affect your bounce rate.

Finally, assign the JavaScript error trigger (that you have previously created) to this Universal Analytics tag. Save the tag, refresh/enable the preview mode.

If you want to test this, you can add this code (temporarily!) to a page via content management system:

<script>
  setTimeout(function(){ 
      jstestingvarwithalongname.push({'key' : 'value'}); 
  }, 2000);
</script>

When you save the page and refresh it (but before that, refresh or enable the GTM preview and debug mode), you should see the JavaScript error in the GTM debug console.

Remember, the aforementioned line of code intentionally contains a JS error. Remove it immediately after the test is done.

#1.2. Why is it useful?

If your developer is not tracking JavaScript errors with a dedicated tool (like TrackJS), JavaScript Error tracking with Google Tag Manager is definitely better than nothing (of course, you should not think this is 100% accurate).

You can track JS errors as negative goals and then see the number of sessions that had at least one error (more on negative goals — later in the blog post).

Another idea: Sequence segments. For example, show all the sessions that entered the checkout and then had a JavaScript error but did not make a purchase.

This segment is more useful for those businesses where customers are usually converting in the same session they arrive.

These are just several ideas and everything depends on your imagination.

#2. Track 404 Errors with Google Tag Manager

Another type of error that you can track with Google Tag Manager is 404, a.k.a. Page Not Found. I have a separate blog post (covering other alternatives too) for that but here are some of the highlights + new ideas.

There are several different ways how to tackle 404 error tracking. I’ll mention two:

  1. Sending a hit-scoped custom dimension to GA (Referrer) and then using it as the secondary dimension in GA reports. This works if “Page not found” error can be distinguished by the page title
  2. Asking a developer to push the 404 event to the Data Layer

#2.1. Hit-scoped custom dimension – Referrer

This method will be useful if the page title of 404 pages contains “Page not found”, “Page missing” or some other phrase that lets you easily identify that a visitor has landed on a 404 page.

How can you check that? Open a website you’re working on, and add some gibberish at the end of the URL, e.g. https://www.youwebsite.com/posts/somenonsense

Are you redirected to a 404 page? What is the title of the page? (you can check that in the browser tab):

So if you indeed see something meaningful (and related to “page not found”) here, continue reading. By the way, huge thanks to Charles Meaden who mentioned this idea in one of my previous blog posts about the Referrer Variable in Google Tag Manager.

#2.1.1. Custom Dimension in GA

In your Google Analytics, you will need to create a custom dimension. Go to Admin (click the gear icon in the bottom left corner of the GA interface) > Property column (make sure you have selected the needed property) > Custom Definitions > Custom Dimension > New Custom Dimension.

Enter the following settings:

  • Name: CD – Referrer (or you can call it just “Referrer”, it’s up to you which Naming Convention to use)
  • Scope: Hit

Once you do that, you will see the number (index) of the custom dimension. Remember it. We’ll need it quite soon.

#2.1.2. GA Settings Variable

I really hope that you already are using this variable in your GA/GTM setups. If you don’t, read this guide. If you do, then do the following:

  • In the variable (that is used by your Universal Analytics tags), click More Settings > Custom Dimensions
  • Enter the index number of your Custom Dimension (for example “5” without quotation marks) in the left column and {{Referrer}} the right one (this variable is enabled in the GTM container by default).

Once this is done, together with every hit (event, pageview, etc.) you will be sending the value of Referrer. In a nutshell, this variable passes the web address of the previous page.

This is useful because you can then better understand where are people coming from to that 404 page and, therefore, will be able to fix the issue sooner.

How can you see that data in GA reports? Go to Behavior > Site Content > All Pages.

Change the primary dimension to Page Title

And then add the CD – Referrer (or whatever you named it) as a secondary dimension.

Finally, in the search field enter “Page not found” (or whatever your website uses as a title of the 404 page).

Voilà! You now have a report of “Page not found” and you also see the previous page that a visitor was on (meaning that those previous pages probably contain broken/outdated links).

Important: this Custom Dimension will NOT affect your past data. Only new hits to GA will be sent together with a “Referrer” custom dimension.

Also, you can create custom GA reports with more dimensions (columns) at the same time:

  • Page title
  • Page
  • CD – Referrer

#2.2. Ask a developer to push the 404 error to the Data Layer

If the previous option did not work for you, here’s another one. Whenever a visitor lands on a page that contains a 404 (page not found) error, ask a developer to activate the following code (preferably, before the GTM container snippet):

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
  'event': 'error',
  'errorType': '404 - page not found'
});
</script>

P.S. You are free to use different values for those keys that match your own naming convention.

This code will push the error information to the Data Layer.

Once a developer implements the code, you will need to:

  1. Create a Custom Event Trigger
  2. Create a Data Layer Variable
  3. Create a Google Analytics Event tag that sends the 404 error to GA as an event (non-interaction)

First, let’s start with a trigger. Go to Triggers > New > Custom Event Trigger and enter the following settings:

Enter the value of the “event” key in the “Event name” field. If you used my code example, then enter “error” (without quotation marks).

Then, the Data Layer Variable. Go to Variables > User-defined Variables > New > Data Layer Variable. Enter the following settings if you have precisely copied my code example:

Important: event names are case-sensitive in GTM.

Last but not least, Universal Analytics (GA) tag. Go to Tags > New > Universal Analytics and enter the following settings:

This should also be configured as “Non-interaction hit: true”.

Don’t forget to test the setup with the GTM preview and debug mode + publish the changes after that.

#3. Checkout Errors

The third group of errors that should definitely get your attention is checkout errors. I’d say that these are one of the most important ones because the visitor/user is very close to the conversion (e.g. purchase, signup, etc.).

Your goal is to reduce friction/struggle as much as possible.

What kind of errors should you track? Consult with a developer of that checkout what is possible.

Here are some ideas:

  • Form-related errors (like “some required fields are not filled in: first name, address”)
  • Form-field-related errors (like “invalid shipping address”)
  • Payment-related errors (like “insufficient funds” or “card declined”) (just make sure things like credit card data is not tracked)

After identifying groups of errors that you want to track, ask a developer to push those errors to the Data Layer, here’s a sample code:

<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
  'event': 'error',
  'errorType': 'checkout error', // this value should depends on the type of error, e.g. form error, checkout error, etc.
  'errorMessage' : 'card declined' // some descriptive message about the error
});
</script>

Then apply the same principle I’ve explained in chapter #2.2. of this blog post, create:

  • Custom event trigger
  • Data Layer variables (for errorType and errorMessage)
  • Google Analytics tag

Here’s what the tag should look like (don’t forget to assign the Custom Event trigger to this tag)

If you have already implemented the 404 tracking with the developer’s help, then you will already have one variable and the trigger. No need to create duplicates for that.

#4. Form Errors (e.g. Registration and Login forms)

There are different ways how to track form errors. Some are more reliable, the others are less. The most robust way is, once again, to cooperate with a developer and ask him/her to push the error data to the Data Layer.

I will not explain this principle all over again. Please revisit chapter #2.2. of this blog post.

In addition to the “Developer + Data Layer” method, here are some other alternatives. Remember, they might be more fragile and cause more significant data inaccuracies:

  1. Track when the error message of the form appears on the screen
  2. Using AJAX form? Check the response when the form is submitted (maybe you’ll find something useful there)

Google Tag Manager Ebook Bundle

#4.1. Using Element Visibility trigger to track form errors

Warning: for this method to work, you will probably need to become familiar with CSS selectors, which is an advanced topic.

So if you have a form that displays an error message (after the form was submitted with an error), here’s what you could do.

First of all, do the right-click on that error message and see what kind of classes or IDs does it have. Once again, I cannot stress this enough: this method will work if you have the right CSS Selector fundamentals in your head.

Here’s an example of what I see after I start inspecting a certain element (P.S. this does not mean that you will see the same thing (because the majority of websites are unique)).

Take a closer look at the class attribute of that error message. One of the classes is wpcf7-validation-errors. We could use that in our GTM trigger.

Go to Triggers > New > Trigger Configuration > Element Visibility and enter the following settings:

In CSS, all classes start with a dot. That’s exactly what we did: we entered .wpcf7-validation-errorsAlso, make sure you enable the “Observe DOM changes” setting.

Let’s test whether the trigger works properly. Save the trigger, refresh/enable the GTM Preview and Debug mode, refresh the page with the form and submit the form with one required field missing (or some other error you know).

You should see the Element Visibility event appear on the left side of the Preview mode panel.

Now, how can you access the text of that error message? The neat trick is that Click Text or Form Text, built-in variables in GTM, return the text of the element that was tracked by the Element Visibility trigger. Learn more about this here.

Now, it’s time for a tag. Go to Tags > New > Universal Analytics and enter the following settings:

I recommend tracking all page errors under the same category “error” (with some exception). I’ll explain my naming convention a bit later in this blog post.

As always, error events in GA should be tracked as Non-interaction hit: true.

Where will you see this event in GA?

  • Realtime > Events (for debugging). If you don’t see the event, read this guide.
  • Behavior > Events > Top Events (keep in mind that the events will not appear here in real-time. You’ll need to wait. Also, don’t forget to include today’s data by adding it in the GA date-picker).

#4.2. Working with an AJAX form? Try this

If your form does not reload the page after it was submitted (or when the error is displayed), there is a chance that the form was built by using the AJAX.

How can you make sure you’re working with an AJAX form? Click this link (credit for this code goes to Bounteous), copy the entire code and paste it into a new Custom HTML tag within your GTM container. Set the tag to fire on All Pages. Save the container, refresh the preview mode and refresh the page where the form is located.

Custom HTML tag will fire on a Pageview event. Don’t worry about that. Now try to submit the form properly. Did the ajaxComplete event appear in the GTM preview mode? Yes? This means you’re working with an AJAX form.

Now try to submit a form with at least one empty required field. Did the ajaxComplete event appear again? If yes, click that event in the preview mode and go to the Data Layer tab.

Scroll down and keep looking for the response section.

Do you see something meaningful there that is related to an error? In my case, I see this (Warning: the data structure of the response might look totally different in your case):

It would be cool to access that status and message values, right? Luckily, we can do that.

#4.2.1. Data Layer Variables

Go to Google Tag Manager > Variables > User-defined Variables > New > Data Layer Variable.

In my example, the status key is in the object response that is in another object called attributes. That is why in the Data Layer Variable, you should enter attributes.response.status (if you have no clue what I’m doing here, read this guide)

Save the variable. Now, it’s time to access the message. Enter attributes.response.message in the Data Layer Variable.

Save the variable.

#4.2.2. Trigger (when the error message is pushed to the Data layer)

Now, it’s time to create a trigger that will be activated when an ajaxComplete will be pushed to the Data Layer and attributes.response.status will equal to validation_failed.

Save the trigger

#4.2.2. Google Analytics tag

And the last step — Universal Analytics tag. Go to Tags > New > Universal Analytics and enter the following settings.

I’ve inserted the attributes.response.message as the Event Label. Every time an AJAX form error will be pushed to the Data Layer, I will pass its text/message to Google Analytics.

Important: If you have named your variables differently (e.g., not dlv – attributes.response.message), then use your naming in the GA tag, not mine.

Save the tag, refresh the preview mode, refresh the page with that form and submit it with an error. Check if the ajaxComplete event was fired and whether it is visible in the GA real-time reports. As for the Standard GA reports, these events will (as usual) appear in the Behavior > Events > Top events report.

#5. Server Error (like 50x, etc.)

When a server error occurs on a page (e.g. “Internal server error” or “Bad Gateway”, etc.), they look like this (pardon me or an old screenshot I found online):

Simple plain text page. However, GTM (or any other snippets) on that page is not available, thus you cannot track them by default. As a solution (I honestly don’t know whether this is the only workaround), you could ask a developer to redirect visitors to a static error page (each error will probably have a unique error page (visually similar but with a different error message)).

For example, if 500 error occurs, a developer could redirect a visitor to a yourwebsite.com/500error.html (or something like that). If 503, then yourwebsite.com/503error.html.

My examples here totally made up. The URLs of your error pages might look totally different. However, keep in mind that only a developer can implement these redirects to error pages.

All error pages could use the same HTML file template with some basic error information and the Google Tag Manager container snippet. The snippet is the key here. Without it, no error tracking will be possible. Some companies even go the extra mile with a custom error page design that might look like this:

If URLs of the error pages contain the error code (e.g. yourwebsite.com/500error.html), you can implement the same method that I’ve explained in #2.1 chapter of this article.

If, however, the URLs aren’t very friendly, e.g., yourwebsite.com/error1.html means 500 error, then you could implement something like this. Create a Lookup Table or Regex Table variable that will check the Page Path and will return a more meaningful/readable value.

#5.1. Lookup Table Variable

For this example, I will use a Lookup Table variable (that will be looking for exact matches).

A hypothetical situation. Our website has 5 error pages for different types of server errors:

  • mywebsite.com/error1.html is for error 500 (if you are not familiar with error codes, here they are)
  • mywebsite.com/error2.html is for 502
  • mywebsite.com/error3.html is for 503, etc.

Here what we could do. In GTM, go to Variables > User-defined Variables > New > Lookup Table. Choose {{Page Path}} as an input variable. Then create separate rows for each error page.

Since we will be working with a {{Page Path}}, we will need to enter what comes after the slash in the URL, e.g. error.html. Let’s do that:

Then, on the right side of each column enter the output that you want to use (in other words, we will turn the ambiguous error.html into 500 error).

If in the future, you plan to implement more error page templates, it’s a good practice to set the “default” value of the table variable. If none of the conditions/rows are met, this variable will default to the {{Page Path}}.

Save the variable.

#5.2. Trigger

Now, let’s create a trigger that will be activated when the visitor loads an error page. Go to Triggers > New >Trigger Configuration > Pageview and enter the following condition:

In our case, Page Path or an error page starts with “error” and ends with “.html”.

#5.3. Tag

Finally, let’s create a Google Analytics event tag that will send the error to GA. Go to Tags > New > Universal Analytics and enter the following settings.

With the help of the Lookup Table variable, you will be sending the actual error codes to GA.

Assign the pageview trigger to this tag, save it. Don’t forget to test and then publish your changes.

Checking Error Data in Google Analytics

Now, it’s time to check your error data in Google Analytics. If you were tracking them as events, you will find them in Behavior > Events > Top Events report. If you followed my naming convention, error Event Category is the one that you should be looking for.

Just keep in mind that:

  • This data does not appear immediately. You will still need to wait (sometimes 15 minutes, sometimes hours. Start panicking after 24 hours.).
  • By default, GA standard reports do not include today’s data. So don’t forget to include it in the date picker.

If some of the errors are tracked as pageviews (e.g. like in #2.1. chapter), then you will find that data in Behavior > Site Content > All Pages. Switch to Page Title primary dimension and then add any secondary dimension if you need it.

Several Tips Regarding Error Naming Convention

This is NOT some hard rule that you MUST follow. It’s up to you how will you name your events in GA. But my personal preference is to group all errors under the Event Category error. JavaScript errors can be an exception and I can treat them as a separate event category (because there is more information that you can get from the JS error trigger). So, it’s up to you to decide.

Then the Event Action would be the type of an error, e.g.:

  • checkout error
  • server error
  • 404 error
  • form error (for general landing page opt-ins)
  • registration error
  • login error, etc.

Event Label should be used for the description of the error. What exactly was the error? For example:

  • If the error is in the checkout, an error message/text would be valuable (like “credit card declined”)
  • If the error was server-side, then the error code (e.g. 503) and the location (URL) would be nice (or at least the error code)
  • If the error is related to a form, then I’d like to know the error text

You get the idea. But once again, these are just my thoughts. You are free to choose a different naming convention.

Subscribe and Get the Ebook - Real Book Img - GTM for Beginners

Treating Errors as Negative Goals in Google Analytics

Usually, goals are treated as positive (for a business) interactions that a visitor/user completed on a site. But it does not always have to be that way. It also makes sense to track a negative conversion rate (shout out to Mikko who was spreading this message in 2019).

What is the percentage of your sessions where visitors/users/customers had at least one error in the checkout? 20%? I think you should take a closer look at that.

If you want to treat every error (that is event-based) that was tracked on a page (and if you followed my naming convention), you could just go to GA Admin (in the bottom left corner) > View column > Goals and create a goal with the following settings:

  • Custom template
  • Name – anything you want
  • Type – Event
  • Event conditions:

This will treat any event of which Event Category equals to error.

If you want to be more specific and track only, say, checkout errors as negative goals, you can enter goal settings similar to these ones:

Once you set the goal, you can find them in multiple reports within Google Analytics, for example, Acquisition > All Traffic > Source/Medium

Or Conversions > Goals > Overview

GA Custom Alerts

I will not dive deeper into how to configure them. Instead, you can read this guide. But I still wanted to mention that such functionality exists. You can configure GA to send you email notifications if the number of certain errors on a page reaches a certain threshold.

Rule of thumb: set alerts only for the most essential problems like server errors or checkout. I would not personally monitor JavaScript errors with an alert because in many cases, users might not even notice that such error has occurred.

If your thresholds for alerts are too low, you will be overwhelmed by the number of notifications and eventually, will start ignoring them. It takes some time to find the proper (not too high but not too low either) threshold.

Final words

These were some of the ideas about Error Tracking with Google Tag Manager. Every business is different, therefore, types of errors that you can/will measure will also be different.

Personally, I always try to track:

  • Form-related errors
  • Checkout errors
  • Registration errors
  • 404 errors

The first three are directly related either to revenue or lead acquisition (that may eventually lead to revenue increase). 404 errors are quite easy to track and may help you identify missed opportunities when a visitor lands on your page, finds nothing and bounces.

Got something to add? Use the comments section below!

Back back to the friggin’ basics. Almost two years ago, I wrote a two-parter on how to have fun with Google Tag Manager: Part 1, and Part 2. The first part had a nice exercise for tracking JavaScript Errors as Google Analytics Events, using the recently published “JavaScript Error Listener” Tag.

Well, that was in GTM V1. Now we’ve been smoothly sailing with the wonderful new interface for well over a year, and it’s time to update some of these nifty tricks. In this #GTMTips post, I’ll show you how to track uncaught JavaScript errors in the new interface, plus give you some tips on the overall process.


X


The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!

Tip 43: Track JavaScript Errors As Events

Track JavaScript Errors As Events In Google Tag Manager

The process is actually really simple. Much easier than it was in the previous Google Tag Manager interface.

By the way, uncaught refers to an error which hasn’t been captured and handled by any of the scripts on the page. The most common way to catch an error is to use try...catch blocks around your code, which capture any errors which bubble up to the context where you have the block. If an error makes its way through without having been caught in any way, it will trigger the JavaScript Error Trigger. Thus it’s a good way to audit your current error detection methods, too!

Anyway, you start by making sure the Built-In Variables are activated.

Built-In Error Variables

If you’re curious about these Built-In Variables, check the relevant section of my Variable Guide For Google Tag Manager.

Next, head on over to Triggers, and create a new one:

JavaScript Error Trigger

I’m going to let the Trigger fire on “All JavaScript Errors”, but be sure to read to the end of this post for tips regarding this selection.

Finally, you need a Google Analytics Event Tag, which collects and concatenates all this information. Here’s what I use:

Google Analytics Error Tag

An example result using these settings would be something like:

Event Category: JavaScript Error
Event Action: Uncaught ReferenceError: appear is not defined
Event Label: 1255: https://www.simoahava.com/scripts/bundle.js

I’m sending the event as Non-Interaction: True, because it’s not a user interaction, and I don’t want it to be counted as such.

And that’s it for the implementation!

Now, there are some things you might want to consider when implementing this on your own website. The next chapter will tackle these issues.

Tips

Tracking JavaScript Errors can be quite the bipolar experience. On the one hand, it’s just a good, solid developer attitude to want to know about what’s breaking up or already broken on your site. On the other hand, it can cause a deluge of Events in your Google Analytics profile, leading to sessions reaching their hit limits and severe sampling issues. So here are a couple of tips to manage it all.

1. Track errors as Google Analytics Goals

“Track ERRORS as GOALS, what has he been smoking?!” I hear you exclaim. Yeah, it’s not a business goal, but goals can also be negative goals. The reason I’m interested in this particular negative goal, is because I want to see a Conversion Rate for sessions with JavaScript Errors. This will allow me to do all sorts of cool analyses on how the error rates are fluctuating over time. To set up the goal, you can use the following settings:

JavaScript Error As GA Goal

Next, you can create an Alert, which sends you an email every time the number of JavaScript Errors has gone up significantly on your site:

JavaScript Error Google Analytics Alert

Now you’ll get an email every time there’s a significant increase in the number of JavaScript Errors recorded on your site.

2. Use Environments or the Debug Mode

Tracking every single uncaught JavaScript error can lead to a deluge of hits. The modern website is best known for the number of errors it dispatches, not the fancy UI or the awesome new framework it utilizes. To keep the number of errors down, you might want to delimit them to only fire in a specific environment, or when in the Debug Mode. You could, for example, allow the Error Trigger to work only in the staging environment.

JavaScript Error in Environments or Debug Mode

This way only errors triggered by your testers and developers will be recorded. The downside, of course, is that it’s not an authentic setting, and no matter how much you test and debug, you will always miss some things.

3. Add manual sampling

Another way to prevent every single error from dispatching is to manually sample the hits that are sent to Google Analytics. You could, for example, only let the Trigger fire for 50% of recorded errors. You can use the Random Number Built-In Variable here:

Random Number sampling for Error Trigger

The trick is to only fire the Trigger when the Random Number Variable returns a number that ends in 0, 1, 2, 3 or 4. That’s 50% of the possible numbers it can end in.

Naturally, the downside here is that you might miss some outlier errors, which only pop up every now and then. But you should still catch most of the significant ones.

4. Script Error

If your site is using JavaScript files loaded from external content distribution networks, the messages and line numbers of the errors dispatched in these external scripts are not exposed in the browser. This is a reality you’ll have to work with. There’s no way to identify where and what error took place, as the browser will only dispatch the nondescript “Script Error.” message with a line number of 0. The URL of the script is still exposed, though, and you can use that to narrow down the possible errors.

Script Error

It’s a good idea to host as many scripts as possible on your own website. Not only will you know more about the errors that are thrown, but also being subservient to an external CDN can introduce security issues, if the third party decides to add some malicious or dangerous code to the library you’re using (or if they’re hacked).

Summary

I hope this tip has been useful. Tracking errors is one of the ways to make sure that your website is catering an optimized experience for your visitors. Google Analytics provides a great tool for tracking these errors, because it also lets you create session- and user-scoped segments around error events. With those segments, you can start analyzing the actual business impact of errors thrown on the site.

An error in the eCommerce checkout funnel can be destructive to your business, and using Google Analytics for detection can help you get on top of things before you’ve lost too much money.

Передача ошибок java script сайта в google analytics через tag manager

Эта статья подойдет для в всех тех, кто не сильно разбирается в java script , но хочет что бы сайт работал на все 100 % без ошибок. С помощью google tag manager мы сможем настроить передачу данных об ошибках js, которые есть на сайте в google analytic. В результате вы получите пользовательский отчет с ошибками js, который можете переслать программисту  для исправлений.

Хочу отметить, что tag manager фиксирует не все ошибки js на сайте. Но это лучше чем ничего. При том, что настройка занимает около 10 минут.

Переходим к настройке:

В gtm нам нужно активировать некоторые переменные, создать триггер и тег а в аналитиксе настроить пользовательский отчет.

Переходим к настройкам в gtm

1.Активируем встроенные переменные:

Переходим в раздел «Переменные» /// настроить /// проверяем переменные – нужно, что бы они были включенные.

Error Message  — название ошибки js

Error Url  — url страницы, где была допущена ошибка

Error Line  — номер строки в которой, была допущена ошибка

2.Создаем триггер

Название: errors Js

Тип триггера: Ошибка JavaScript

Триггер активируется на следующих страницах: Все ошибки JavaScript

3.Создаем тег

Название: Errors JS

Тип тега: Universal Analytics

Тип отслеживания: событие

Категория: Errors js

Действие: выбираем переменную «Error Message» —  название ошибки js

Ярлык: выбираем сразу две переменные

переменную  Error Url  — url страницы, где была допущена ошибка

и в скобках выбираем переменную Error Line  — номер строки в которой, была допущена ошибка

В результате через ярлык  в гугл аналитикс будет передаваться переменная  url страницы, а в скобках  переменная номера строки с ошибкой

Не взаимодействие: True

Включаем переопределение настроек в этом теге

Идентификатор отслеживания: cod ua – созданная переменная

Триггер активации тега: выбираем Errors js – который  мы предварительно создали

Отправляем на публикацию.

Настроим пользовательский отчет в google analytics

Схема

Тип: простая таблица

Параметры: категория событий, действие по событию, ярлык события

Показатели: всего событий, уникальные события

Фильтр: категория событий точное соответствие  Errors js

Смотрим отчет

Из отчета мы видим название ошибки, url страницы с ошибкой и в скобках номер строки.

Можно выгрузить этот файл в excel  и отправить на обработку.

Анализируйте, делайте выводы, принимайте решения и действуйте!

The following two tabs change content below.

  • Автор
  • Последние статьи

Сегодня посмотрим как можно настроить отслеживание JavaScript ошибок на сайте с помощью Google Tag Manager, и оповещать о них прямо в Google Analytics. Иногда это бывает очень полезно, так как клиенты «любят» обновлять и улучшать свой сайт новыми фичами, а программисты — люди которые регулярно совершают ошибки (мне ли не знать). Иногда такие ошибки могут быть довольно серьезными, и повлиять на работоспособность сайта, а в итоге и на его конверсии.

Настройка довольно проста и разбита на несколько шагов, давайте начнем.

1. Убедитесь, что включены переменные JS ошибок:

2. Следующим шагом необходимо создать триггер:

В нем мы указали тип: JavaScript Error — то есть запускаться при любой JS ошибке. И в условии — реагировать на все ошибки, так как нам нужно получать все уведомления об ошибках, а не конкретные (при надобности вы сможете их уточнить).

3. И в конце мы создаем тег Google Analytics, который собственно и будет отправлять все уведомления (события) об ошибках в наши отчеты:

Обратите внимание: я использую переменную (константу) {{UA}} вместо tracking ID. Так гораздо проще указывать свой UA ID из Google Analytics, не вводя его повторно много раз, что сокращает  время на настройку и шанс ошибиться.

В action указано само сообщение ошибки (то, что можно увидеть в консоли разработчика в вашем браузере).
В label через двоеточие мы отправляем в какой строке была ошибка и на какой странице. Такой подход сильно упростит отладку ошибок на сайте, и вы сразу сможете сказать разработчикам что и где поломалось. По количеству событий в отчетах вы также увидите когда именно это случилось.

  • Можно поставить отслеживание ошибок — как цель в Google Analytics! Естественный вопрос — зачем? Ответ на него прост, тогда вы можете настроить автоматические уведомления по почте, например, когда количество ошибок увеличилось на 20%.
  • Можно отслеживать не все ошибки (чтобы не расходовать лимиты аналитикса), а добавить семплирование следующим способом:

    Суть его в том, что тег будет срабатывать в половине случаев, то есть когда в конце случайного числа будет цифра от 0 до 5.

Status
Not open for further replies.

  • #1

Last edited by a moderator: Mar 13, 2021

rgd1101



Nov 7, 2011



69,653



3,204



162,240

6,865


  • #2

what site are you on?
malware scan your system?
browser up to date? windows up to day?

  • #3

what site are you on?
malware scan your system?
browser up to date? windows up to day?

I am not on any site ,script error pops up on desktop at start up. Virus & system up to date. Thanks Mark.

  • #4

Had the same popup-problem — In my case, I just disabled the autostart via Taskmanager of my Telekom-Cloud-Software called «Magenta Cloud»… 🙄

Status
Not open for further replies.
  • Advertising
  • Cookies Policies
  • Privacy
  • Term & Conditions
  • Topics

Загрузка…

Всякий раз, когда вы создаете теги через Диспетчер тегов Google, важно всегда проверять свои реализации. Хотя мы все надеемся, что тестирование пройдет гладко для всех наших тегов, чтобы они срабатывали, как ожидалось, это только вопрос времени, пока тег будет вести себя не так, как предполагалось.

В этой статье я рассматрю пять общих ошибок, которые заставляют теги срабатывать неправильно и возможные решения этих ошибок.

1. Почему мой тег срабатывает неправильно?

Иногда тег не запускается там, где он должен из-за множества триггеров или нескольких правил в триггере.

Решение:

Поскольку все теги срабатывают в результате конфигураций триггеров, это, как правило, лучшее место для начала, когда теги не срабатывают по назначению.

Начните с двойной проверки настроек триггера. При этом помните, что при добавлении нескольких триггеров в тег будет срабатывать тэг всегда, когда будет встречен набор правил для ЛЮБОГО триггера. Это контрастирует с добавлением нескольких правил к одному триггеру, в соответствии с которым все правила должны выполняться для запуска триггера. Это объясняется с помощью приведенного ниже примера:

На приведенном ниже рисунке показана настройка тега, который запускается либо по ссылке, содержащей адрес электронной почты, либо по ссылке, содержащей «mailto:». Для того, чтобы тег срабатывал, необходимо выполнить только одно из этих условий.

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

Если есть два правила, указанные в одном и том же триггере, то оба правила должны быть выполнены для запуска триггера. В приведенном ниже примере показано, как настроить триггер, который срабатывает только в том случае, если ссылка на клике содержит как адрес электронной почты, так и «mailto:».

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

2. Почему мой тег Click не срабатывает при нажатии?

Вы реализовали триггер щелчка на основе идентификатора, класса или пользовательского атрибута элемента click, но он не срабатывает при нажатии на целевой элемент.

Решение:

При внедрении триггеров кликов важно выяснить, на каком элементе клик зарегистрирован. Когда у вас есть элемент, вложенный в другие элементы, возможно, что клик может регистрироваться на одном из нескольких элементов.

В приведенном ниже примере клики могут регистрироваться на изображении, в диапазоне, div «generic_class» или div «track_me» (в зависимости от макета). Если вы пытаетесь отслеживать любой щелчок в div «track_me», важно учитывать клики на любом из его дочерних элементов (любой элемент в div).

<div id = “track_me”>

   <div class = “generic_class”>

      <img src = “images / blog_pic.jpeg”>

      <span> Некоторые тексты </span>

   </div>

</div>

Для этого вам необходимо расширить условия, связанные с щелчком, чтобы также включить элементы в div «track_me». Этого можно добиться с помощью следующего CSS-селектора в вашем наборе правил. «*» Соответствует всем элементам в div «track_me».

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

3. Почему мои параметры Data Layer неверны?

Иногда переменные, объявленные в слое данных, не заполняются при загрузке страницы, или событие Data Layer не запускает соответствующий триггер в GTM.

Решение:

Если вы реализуете теги, которые полагаются на переменные уровня данных, начните с того, что уровень данных был правильно реализован. Чтобы слой данных был доступен для тегов загрузки страницы, он должен быть объявлен, и все переменные должны быть заполнены до загрузки контейнера GTM. Если уровень данных не заполняется до загрузки контейнера GTM, то ни одна из ваших переменных уровня данных не будет определена.

Чтобы проверить это, включите режим отладки в GTM и проверьте уровень данных для события Просмотр страницы. На приведенном ниже изображении показано, как это выглядит, когда слой данных не был заполнен на странице или был заполнен после загрузки контейнера GTM.

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

С другой стороны, события уровня данных должны быть перенесены в GTM только после загрузки контейнера GTM. Если контейнер не загружен и вы пытаетесь нажать событие на уровень данных, он не будет перекодирован в GTM. Если вы не реализовали слой данных на своем веб-сайте, вы также увидите ошибку JavaScript на консоли разработчика, сообщив вам, что dataLayer не определен.

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

4. Почему мои изменения не видны?

Вы внесли изменения в свой контейнер GTM, но это не отражается на ваших усилиях по отладке.

Решение:

Хотя это не проблема технической реализации, неопубликованные версии контейнера GTM приведут к тому, что теги не будут активироваться. Это не может быть обычной проблемой, когда в контейнере GTM работает только один человек. Однако, когда несколько человек работают в одном и том же контейнере, необходимо следить за тем, что является Live версией.

К счастью, это очень легко сделать с вкладкой «Версии» в GTM. Нажмите вкладку «Версии» в заголовке, и вы можете проверить, какая версия в прямом эфире. Она полагается на вас и вашу команду, используя логическое и простое соглашение об именовании для ваших версий.

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

5. Почему мои теги не регистрируются в Google Analytics?

Представьте, что ваши тэги правильно работают в GTM, но вы не видите никаких данных в своем инструменте аналитики.

Решение:

В последнем пункте рассматривается последний шаг процесса тестирования, а именно проверка данных в результате вашего тега в вашем инструменте аналитики. Это особенно удобно в Google Analytics, где вы можете легко проверить данные в отчете в режиме реального времени. Если все ваши теги срабатывают правильно в GTM, но данные не записываются в GA, вероятно, стоит проверить свой идентификатор свойства GA (UA-XXXXX-X).

Поскольку это переменная, которую необходимо вводить в каждый тег GA, существует вероятность того, что введен неверный идентификатор. Чтобы уменьшить этот риск, я предлагаю создать настраиваемую переменную содержимого, содержащую идентификатор свойства GA.

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

Это позволяет ссылаться на переменную с использованием синтаксиса {{variable name}} всякий раз, когда вы используете его в своих тегах.

Здесь должно быть изображение для статьи - 5 Общие проблемы менеджера тегов Google и способы их устранения

Если у вас есть какие-либо вопросы по этим проблемам, пожалуйста, напишите комментарий ниже или отправьте мне электронное письмо.

  • Share 0
  • +1
  • LinkedIn 0

Понравилась статья? Поделить с друзьями:
  • Google play транзакция отклонена ошибка
  • Google play произошла ошибка повторите попытку позже
  • Google play ошибка при скачивании
  • Google play ошибка попробуйте еще раз
  • Google play ошибка обновления приложений