Skip to content

LdeAlejandro/CodeTagGenerator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

48 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Code Helper Generator

Code Helper Generator is a tool created to streamline and simplify the process of tracking Google Ads and Analytics conversions. It automatically generates code snippets tailored for commonly used tracking functions, making it easy for users to monitor key actions through Google Tag Manager or gtag.

Purpose

This tool was developed with two main goals in mind:

  1. Speed up code generation: By offering pre-configured options, Code Helper Generator accelerates the creation of tracking code, helping to implement frequently used tracking snippets faster.
  2. Assist with code creation: Designed with users in mind who may find coding challenging, this tool simplifies generating precise tracking code, reducing the potential for errors.

Key Features

  1. Activator Options: Choose from a comprehensive list of event types, including form submissions, button clicks, link tracking, and chat messages, tailored for Google Ads and Analytics tracking needs.
  2. Automatic Code Generation: Instantly generate and copy optimized JavaScript code for tracking events.
  3. Data Layer and Event Integration: Enables seamless integration with GTM or gtag for enhanced tracking of user interactions.

How to Use

  1. Open the tool directly through this link: Code Helper Generator.
  2. Select the activator type from the list of options to define the action you want to track.
  3. Enter additional details if needed, such as URLs or specific selectors.
  4. Click "Generate Code" to create the JavaScript code snippet.
  5. Copy the code using the copy button and implement it in your project.

Additional Tips

  • Testing: The generated code can often be tested directly in the browser console to ensure functionality.

  • Implementation: Use the generated code with Google Tag Manager or directly on the client’s website for effective tracking of conversions and user interactions.

  • Be aware that some code may not work on specific platforms, and you should check the platform's documentation to understand how to track Google Ads or Analytics conversions.

Code Helper Generator Documentation

This document provides detailed explanations of the code snippets generated by Code Helper Generator. Each snippet is tailored for specific tracking events and actions, compatible with Google Tag Manager (GTM) or gtag.

Each code snippet is designed to improve tracking capabilities through Google Tag Manager and Analytics. Adjust the element selectors and messages to match your site’s structure and ensure accurate tracking.

Snippets Documentation

1. Form Submission with Thank You Message (formThnkMsg-code)

<script>    
var googleForm = 'Thank you for your message!';
(function googleFormValidation() {
 if (document.body && document.body.innerText.includes(googleForm)) {
  console.log("Form Submitted");
  dataLayer.push({
    'event': 'event_name'
  });
 } else {
  setTimeout(googleFormValidation, 500);
 }
})();
</script>

Description: Tracks a form submission by detecting a thank-you message on the page. Useful for forms that don’t redirect after submission.

How it works: The script checks if the thank-you message is present. When found, it logs "Form Submitted" and pushes a custom event (form_submission_event) to the dataLayer.


2. Link Click Tracking (link-click-code)

<script>  
window.addEventListener('click', function (e) {
 if (e.target.closest('[href*="example.com"]')) {
   console.log('example.com has been clicked');
   dataLayer.push({
    'event': 'event_name'
   });
 }
});
</script>

Description: Triggers when a specified link is clicked, such as for tracking clicks to external sites or specific links within a page.

How it works: The script listens for clicks and checks if the clicked link matches a specified URL pattern. When matched, it logs the click and pushes a link_click_event to the dataLayer.


3. ID Click Event (id-click-code)

<script>
document.querySelector('#button_id').addEventListener('click', function () {
 console.log('Button clicked');
 dataLayer.push({
   'event': 'event_name'
 });
});
</script>

Description: Monitors clicks on an element identified by its ID. This is helpful for tracking actions on specific buttons or inputs.

How it works: Attaches a click event listener to the element with the specified ID, logging the click and pushing an id_click_event to the dataLayer.


4. Class Click Event (class-click-code)

<script>
document.querySelector('.button_class').addEventListener('click', function () {
 console.log('Button clicked');
 dataLayer.push({
   'event': 'event_name'
 });
});
</script>

Description: Tracks clicks on elements with a specific CSS class, useful when multiple elements share the same class and need collective tracking.

How it works: Adds a click event listener to elements with the specified class. Upon click, logs the action and pushes a class_click_event to the dataLayer.


5. Attribute Click Tracking (attribute-click-code)

<script>
document.querySelector('[name="checkout"]').addEventListener('click', function() {
    console.log('Attribute element clicked!');
    dataLayer.push({
      'event': 'event_name'
    });
});
</script>

Description: Monitors clicks on elements with a specified attribute, like tracking clicks on buttons with a name attribute set to "checkout".

How it works: Targets elements with a particular attribute and logs the click while pushing an attribute_click_event to the dataLayer.


6. Multiple Elements Attribute Click (forEachAttribute-click-code)

<script>
document.querySelectorAll('[name="add-to-cart"]').forEach(function(btn) {
  btn.addEventListener('click', function() {
    console.log('Add-to-cart button clicked!');
    dataLayer.push({
      'event': 'event_name'
    });
  });
});
</script>

Description: Tracks clicks across multiple elements sharing the same attribute, commonly used for tracking multiple "Add to Cart" buttons.

How it works: Loops through each element with the specified attribute, adding a click listener that logs the action and pushes a foreach_attribute_click_event to the dataLayer.


7. Enhanced Form Submission with Validation (formThnkMsgEnhanced-code)

<script>   
var g_EC = { email: '[type="email"]', phone_number: '[type="tel"]' };
window.g_setupEC = Object.create(null);
window.g_ECObj = Object.create(null);
var g_countryCode = 'your country codeexample: 55';
document.addEventListener('input', g_setup_ECObj);
function g_setup_ECObj(e) {
  var input = e.target;
  for (i in g_EC) {
    if (input.matches(g_EC[i])) g_setupEC['g_' + i] = input.value;
  }
  g_save_toECObj();
}
function g_save_toECObj() {
  for (i in g_EC) {
    if (g_setupEC['g_' + i] && i === 'email' && g_validateMail(g_setupEC['g_' + i])) window.g_ECObj[i] = g_setupEC['g_' + i];
    if (g_setupEC['g_' + i] && i === 'phone_number') {
      var cleanedPhone = g_validatePhone(g_setupEC['g_' + i]);
      var finalPhone = cleanedPhone.includes('+') ? cleanedPhone : cleanedPhone.startsWith(g_countryCode) ? '+' + cleanedPhone : '+' + g_countryCode + cleanedPhone;
      finalPhone.length >= 11 && finalPhone.length <= 15 ? (window.g_ECObj[i] = finalPhone) : delete window.g_ECObj[i];
    }
  }
}
function g_validateMail(email) {
  return /\S+@\S+\.\S+/.test(email);
}
function g_validatePhone(tel) {
  return tel.replace(/\D/g, '');
}
g_save_toECObj();
    (function googleFormValidation() {
      if(document.body.innerText.includes('you form thanks msg') && g_ECObj.email ) {
        console.log("¡Tus datos se enviaron con éxito!");
        dataLayer.push({
            'event' : 'event_name'
        })
      }else {
        setTimeout(googleFormValidation, 500);
      }
    })();
</script>

Description: Monitors form submissions with extra data validation for email and phone number, providing enhanced tracking capabilities.

How it works: Captures and validates user input in email and phone fields, then pushes an enhanced_form_submission_event to the dataLayer if validation passes.


8. WhatsApp Link Click Tracking (whatsapp-link-click)

<script>  
window.addEventListener('click', function (e) {
  if (e.target.closest('[href*="web.whatsapp"]') || e.target.closest('[href*="api.whatsapp"]') || e.target.closest('[href*="wa.link"]') || e.target.closest('[href*="wa.me"]')) {
    console.log('web.whatsapp has been clicked');
    dataLayer.push({
      'event': 'whatsapp'
    });
  }
});
</script>

Description: Tracks clicks on WhatsApp links, including wa.me and web.whatsapp links.

How it works: Checks for clicks on links containing WhatsApp URLs and pushes a whatsapp_click_event to the dataLayer when clicked.


9. Telephone Link Click Tracking (tel-link-click)

<script>
window.addEventListener('click', function (e) {
  if (e.target.closest('[href*="tel:"]')) {
    console.log('Phone link clicked');
    dataLayer.push({
      'event': 'tel_click_event'
    });
  }
});
</script>

Description: Monitors clicks on tel: links to track phone call initiation.

How it works: Adds an event listener that identifies and logs clicks on phone links, pushing a tel_click_event to the dataLayer.


10. Email Link Click Tracking (email-link-click)

<script>
window.addEventListener('click', function (e) {
  if (e.target.closest('[href*="mailto:"]')) {
    console.log('Email link clicked');
    dataLayer.push({
      'event': 'mailto_click_event'
    });
  }
});
</script>

Description: Tracks clicks on mailto: links, useful for monitoring email interactions.

How it works: Detects and logs clicks on email links, pushing a mailto_click_event to the dataLayer.


11. HubSpot Form Submission (formHubSpot-code)

<script>
window.addEventListener('message', function (m) {
  try {
    if (m.data.eventName === 'onFormSubmit') {
      console.log('Form has been sent');
      dataLayer.push({ event: 'hubSpotForm_sent' });
    }
  } catch (x) { }
});
</script>

Description: Tracks form submissions on HubSpot forms embedded on the site.

How it works: This code listens for a message event with the eventName property set to onFormSubmit, indicating that the form has been submitted. When this occurs, it logs the submission and pushes an event (hubSpotForm_sent) to the dataLayer.


12. Enhanced HubSpot Form Submission with Email Capture (formHubSpotEnhanced-code)

<script>
window.g_ECObj = Object.create(null);
window.addEventListener('message', function (m) {
  try {
    if (m.data.eventName === 'onFormSubmit') {
      var data_raw = m.data.data;
      window.g_ECObj = data_raw.reduce(function (acc, e) {
        if (e.name === 'email') {
          var gEmail = e.value.match(/\b(\S+@\S+\.\S+)\b/);
          acc = Object.assign(acc, { 'email': gEmail[0] });
        }
        return acc;
      }, {});
      dataLayer.push({ event: 'hubSpotFormEnhanced_sent' });
    }
  } catch (x) { }
});
</script>

Description: This enhanced HubSpot form tracking captures the submitted email, pushing it to the dataLayer along with the event.

How it works: On form submission, it collects the email address if available, then pushes both the event (hubSpotFormEnhanced_sent) and the captured email data to the dataLayer.


13. Wix Chat Message Sent (wixChatmessageSent-code)

<script>
window.addEventListener('message', function(e) {
  var jsonData = JSON.parse(e.data);
  if (jsonData.hasOwnProperty('data') && jsonData.data.eventKey === 'TPA_PUB_SUB_ChatWidget.onMessageSent') {
    console.log("Message Sent in Wix Chat");
    dataLayer.push({ 'event':'wixChat_messageSent' });
  }
});
</script>

Description: Tracks message-sending events in a Wix chat widget.

How it works: This script listens for a specific message event from the Wix chat widget. When a message is sent, it pushes the wixChat_messageSent event to the dataLayer.


14. AmoForms Form Submission (amoformsSent-code)

<script>
window.addEventListener('message', function(event) {
  try {
    var message = JSON.parse(event.data);
    if (message.func === 'amoformsSuccessSubmit') {
      console.log('AmoForm submitted');
      dataLayer.push({ 'event': 'amoforms_formSent' });
    }
  } catch (error) {}
});
</script>

Description: Captures submissions from AmoForms embedded forms.

How it works: Listens for an amoformsSuccessSubmit event message, indicating a successful form submission, then logs and pushes amoforms_formSent to the dataLayer.


15. Calendly Scheduled Event (calendlyScheduled-code)

<script>
window.addEventListener('message', function (m) {
  if (m.data.event && m.data.event.includes('event_scheduled')) {
    console.log('Calendly Appointment Scheduled');
    dataLayer.push({ 'event': 'calendlyScheduled' });
  }
});
</script>

Description: Tracks when a Calendly appointment is scheduled.

How it works: On receiving a message event from Calendly indicating an event was scheduled, it logs the action and pushes calendlyScheduled to the dataLayer.


16. Local Storage Value Retrieval (localStorage-code)

// Example: Setting and getting values in localStorage
var googleValue = document.querySelector("#example").innerText.replace(/\D/g,'') / 100;
localStorage.setItem('googleValue', googleValue);
console.log(localStorage.getItem('googleValue'));

Description: Saves and retrieves values from localStorage for later use, including in GTM if needed.

How it works: Stores a parsed value from an element into localStorage, then retrieves it as needed, such as for tracking purposes with GTM.


17. Upnify Form Submission (upnifyForm-code)

<script>
window.addEventListener('message', function(e) { 
  if (e.data.upWidgeChatCallback) { 
    console.log('Upnify Form Submitted');
    dataLayer.push({ 'event':'upnify_formSubmitted' });
  }
});
</script>

18. Upnify Enhanced Form Submission (upnifyForm-code)

<script>   
window.addEventListener('message', function(e) { 
  if (e.data.upWidgeChatCallback) { 
        window.g_ECObj = Object.create(null);
    g_ECObj.email = e.data.upWidgeChatCallback.correo.match(/\S+@\S+\.\S+/); 
    console.log('Received message with event string:', e.data); 
    dataLayer.push({'event':'upnifySent'})
  }
});        
  </script>

Description: Tracks form submissions from Upnify forms or chat widgets.

How it works: When the upWidgeChatCallback event is detected, it logs the form submission and pushes upnify_formSubmitted to the dataLayer.


19. Shopify Purchase Conversion Tracking (shopifyPurchase-code)

//tag global
<!--  Global site tag (gtag.js) - Google Ads: AW-XXXXX -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-XXXXX"></script>
<script> 
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'AW-XXXXX');
</script> 
//codigo para conversão de compra
 <!-- Event snippet for Test conversion page -->
  <script>
    gtag('event', 'conversion', {
      'send_to': 'AW-XXXXXX/XXXXX',
      'value': {{ checkout.total_price | divided_by: 100.0 }},
      'currency': '***BRL***',
      'transaction_id': '{{ order_number }}',
    });
  </script>

Description: Tracks purchase conversions in Shopify by sending purchase data to Google Ads.

How it works: Triggers a conversion event with purchase details (order number, price, currency) to Google Ads upon a completed Shopify checkout.

19. Shopify Purchase Conversion Tracking (shopifyPurchase-code)

{% assign fa_send_to = 'AW-XXXXX'%}
{% assign fa_include_tax_and_shipping = 'no' %}
{% comment %}DO NOT EDIT BELOW{% endcomment %}
{% if fa_google_coding %}{% assign fa_google_coding = true %}{%- else -%}{% assign fa_google_coding = false %}{%- endif -%}
{% if fa_include_tax_and_shipping == 'yes' %}
{% assign fa_checkout_price = checkout.total_price | divided_by: 100.0   %}
{%- else -%}
{% assign fa_checkout_price = checkout.subtotal_price | divided_by: 100.0  %}
{%- endif -%}
{% assign fa_google_ids = fa_send_to | split: "/"  %}
{% if fa_google_coding == false %}
<script async src="https://www.googletagmanager.com/gtag/js?id={{fa_google_ids[0]}}"></script>
{%- endif -%}
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', '{{fa_google_ids[0]}}', {'allow_enhanced_conversions':true});
 </script>
{% if first_time_accessed %}
<script>
  gtag('set', 'user_data', {
    "email": "{{ customer.email }}",
    "phone_number": "{{billing_address.phone}}",
    "address": {
      "first_name": "{{ billing_address.first_name }}",
      "last_name": "{{billing_address.last_name}}",
      "street": "{{billing_address.street}}",
      "city":"{{billing_address.city}}",
      "region": "{{billing_address.province}}",
      "postal_code": "{{billing_address.zip}}",
      "country": "{{billing_address.country}}"
    }
  });
  
  gtag('event', 'conversion', {
      'send_to': '{{ fa_send_to }}',
      'value': {{ fa_checkout_price }},
      'currency': '{{ currency }}',
      'transaction_id': '{{ order_number }}'
  });
 </script>
{% endif %}

Description: Tracks purchase conversions in Shopify by sending purchase and cliente data to Google Ads.

How it works: Triggers a conversion event with purchase details (order number, price, currency) to Google Ads upon a completed Shopify checkout.

Google Ads Enhanced Conversion Tracking Template

This snippet template sets up a Google Ads global tracking tag with support for enhanced conversions. It configures gtag.js to allow for enhanced conversion tracking, captures user data, and triggers a conversion event.

<script async src="https://www.googletagmanager.com/gtag/js?id=AW-XXXXXXX"></script>  
<script> 
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
      gtag('config', 'AW-XXXXXX'), {'allow_enhanced_conversions':true};
</script>             
            
<script>        
gtag('set', 'user_data', { email: g_ECObj.email, phone_number: g_ECObj.phone_number  });
gtag('event', 'conversion', {'send_to': 'AW-XXXXX/XXXXXX'}); 
</script>

How It Works

  1. Load Global gtag.js Library:

    <script async src="https://www.googletagmanager.com/gtag/js?id=AW-XXXXXXX"></script>

    This line loads Google’s global site tag (gtag.js) asynchronously. Replace AW-XXXXXXX with your Google Ads ID to configure the global tag for your account.

  2. Configure gtag for Enhanced Conversion:

    <script> 
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'AW-XXXXXX', {'allow_enhanced_conversions': true});
    </script>
    • Initializes the dataLayer and sets up the gtag function for pushing events.
    • Sets up Google Ads with your account ID (AW-XXXXXX) and enables Enhanced Conversions for better tracking accuracy.
  3. Capture and Save User Data:

    <script>        
    gtag('set', 'user_data', { email: g_ECObj.email, phone_number: g_ECObj.phone_number });
    </script>
    • Sets user data in gtag, including email and phone number. This information is captured as part of the enhanced conversion setup, improving conversion attribution accuracy.
  4. Trigger the Conversion Event:

    <script>
    gtag('event', 'conversion', {'send_to': 'AW-XXXXX/XXXXXX'}); 
    </script>
    • This triggers a conversion event, sending it to your specified Google Ads conversion label (AW-XXXXX/XXXXXX). This action records conversions linked to this label, useful for tracking goals like purchases or form submissions.

Note: Replace AW-XXXXXXX, AW-XXXXXX, and AW-XXXXX/XXXXXX with your actual Google Ads account ID and conversion labels. This setup should be used on pages where you want to capture conversions, such as a “Thank You” or order confirmation page.

About

Code Helper Generator is a tool created to streamline and simplify the process of tracking Google Ads and Analytics conversions.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published