About cookies on this site

We use cookies to collect and analyse information on site performance and usage, to provide social media features and to enhance and customise content and advertisements. Learn more

Cookie settings

About cookies on this site

Cookies used on the site are categorized and below you can read about each category and allow or deny some or all of them. Learn more

Necessary

Some cookies are required to provide core functionality. The website won't function properly without these cookies and they are enabled by default and cannot be disabled.

Preferences

Preference cookies enables the web site to remember information to customize how the web site looks or behaves for each user. This may include storing selected currency, region, language or color theme.

Analytical cookies

Analytical cookies help us improve our website by collecting and reporting information on its usage.

Marketing cookies

Marketing cookies are used to track visitors across websites to allow publishers to display relevant and engaging advertisements. By enabling marketing cookies, you grant permission for personalized advertising across various platforms.

  • Courses
    • Paid courses
    • Course bundles
    • Free courses
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login
  • Courses
    • Paid courses
    • Course bundles
    • Free courses
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login

June 10, 2020

Extract a Price from a Page with Google Tag Manager

While DOM scraping is not recommended (because it’s quite fragile) in web tracking, sometimes you just have no other choice. Asking a developer to push a certain data point to the Data Layer is always the best practice but in some projects, you have just two options:

  • try to fetch a certain value from the page by yourself
  • or do nothing and continue without that particular data point

In this blog post, I wanted to show you several little scripts that will help you fetch a price if it is a visible element on a page.

This is not designed to fetch all of the prices on a page and build complex-ish objects, etc. Let’s take a step back. This blog post is for those situations where you want to work only with one price.

Where can it be useful?

  • Maybe you want to track an impression of a product and you want to send the price of that product to some tool? If yes, this guide is for you.
  • Maybe you want to track purchases and you want to send the order total to some tracking pixel? If yes, then you will find this guide useful too.

In this blog post, I will be focusing ONLY on how to extract a price from a page, not how to send it to other analytics/marketing tools.

 

Custom JavaScript Variable

In this guide, I will be using a Custom JS variable. Yes, I know that Custom Template would be a better solution but it looks like at the moment, Custom Templates do not allow to access elements on a page. If I’m wrong, please correct me. I’d be happy to create a Custom Variable Template for this.

There are various ways of how websites display prices, e.g.:

  • 12.00 USD
  • $12.00
  • Price: $12,000.00, etc.

Also, your definition of an “extracted price” might be different than mine. Some people just want to get rid of the dollar sign, others want to turn strings to numbers, etc. That’s why I will post several options of the Custom JavaScript code and you’ll have to choose the one that fits your needs the best.

Note: obviously, these codes will not cover ALL of the possible price formatting variations. I was trying to solve the most common situations. So, if you have some edge case, let me know in the comments and I’ll see what I can do.

 

Requirement

To properly implement this solution, you must be familiar with CSS selectors. Usually, the basics are enough. In this guide, I presume that you already have that knowledge.

Subscribe and Get the Ebook - JavaScript for Google Tag Manager

Option #1: If you just want to get rid of text and currency signs

This option will work if the price on your website matches one of the following examples (works with any currency code or sign):

  • some text 12.00 (e.g. Price: 12.00). The Custom JavaScript variable will return a string ‘12.00‘.
  • some text 12.00 some text. The Custom JS variable will return a string ‘12.00‘.
  • $12.00 (applies to other currency signs too). The Custom JS variable will return a string ‘12.00‘.
  • 12.00USD (or some other currency code). The Custom JS variable will return a string ‘12.00‘.
  • 12,000.00 USD or $12,000.00. The Custom JS variable will return a string ‘12,000.00‘

These were the scenarios that I was testing against. And here is the code itself:

function() {
  var priceText = document.querySelector('ENTER_YOUR_SELECTOR');
  if (priceText) {
  var regex = /([0-9.,]+)/;
  if (regex.test(priceText.innerText)) {
    return priceText.innerText.match(regex)[0];
  }
  }
}

Important: you need to change the EDIT_YOUR_SELECTOR part and enter the actual selector of the element that contains the price. For example:

  • if the price element has the class selected-ticket-price, the CSS Selector will be .selected-ticket-price
  • if the price element has the ID order-total, the CSS selector will be #order-total , etc.

Here’s a guide that can help you with CSS selectors. Too confusing? Consider enrolling in my Intermediate/Advanced GTM course and I’ll teach you what the heck this is.

 

Option #2: If you want to get rid of the text, currency signs, and commas

This option will work if the price on your website looks like this (thousands are separate with commas):

  • 12,000.00 USD. The Custom JS variable will return a string ‘12000.00‘.
  • $12,000.00. The Custom JS variable will return a string ‘12000.00‘.

If there is some text before or after the price, it will be automatically removed.

function() {
  var priceText = document.querySelector('ENTER_YOUR_SELECTOR');
  var regex = /([0-9.,]+)/;
  if (regex.test(priceText.innerText)) {
    return priceText.innerText.match(regex)[0].replace(/,/g, '');
  }
}

If we compare this script with option #1, this uses a method replace that will remove all the commas in the extracted price.

Once again, you need to replace the ENTER_YOUR_SELECTOR with an actual selector of the website element that contains a price.

 

Option #3: If you also want the variable to return the number (instead of a string)

Some tools might require you to pass the price not as a string (‘12.99’) but as a number (12.99 — without quotation marks). If that’s your case, you need to use the parseFloat method in the return statement, for example:

function() {
  var priceText = document.querySelector('ENTER_YOUR_SELECTOR');
  var regex = /([0-9.,]+)/;
  if (regex.test(priceText.innerText)) {
    return parseFloat(priceText.innerText.match(regex)[0].replace(/,/g, ''));
  }
}

 

If you already have a price as a variable

What if you already have an unprocessed price as a variable in Google Tag Manager? For example, a Data Layer Variable that returns $12.00?

In that case, you can replace document.querySelector(‘ENTER_YOUR_SELECTOR’) and insert your variable surrounded by double curly braces. Also, get rid of the “innerText” property. The final result:

function() {
  var priceText = {{INSERT YOUR VARIABLE HERE}};
  var regex = /([0-9.,]+)/;
  if (regex.test(priceText)) {
    return priceText.match(regex)[0].replace(/,/g, '');
  }
}

To learn more about how to insert variables in GTM, you can read this guide.

 

Additional tips regarding when to use this variable

Keep in mind that any of these variables will return the proper value ONLY if the price element exists on a page.

  • If the element is rendered when the page is loaded, you can start using it on DOM Ready and subsequent events. DO NOT use it on the Container Loaded (a.k.a. Pageview).
  • If the price element appears dynamically after a particular visitor interaction, start using this variable in your tags on the Element Visibility event (when the price appears) and subsequent events.

To sum up: don’t try to activate your tags (that use these Custom JS variables) when the price element is not rendered on a page yet.

 

Extract a Price from a Page with GTM: Final Words

And that’s it. In this quick guide, I shared several Custom JavaScript snippets that should help you extract a price from a page with the help of Google Tag Manager. If it is possible to ask a developer to push the price to the Data Layer, always go with that option. Consider this blog post as a plan B.

Why is this more fragile? Because DOM scraping is more prone to errors. If developers change the code of the front-end of the website, such tracking solutions can easily break.

Julius Fedorovicius
In Google Tag Manager Tips
7 COMMENTS
soso
  • Jun 10 2020
  • Reply

Hi 👋🏼 Thank you for this post, just amazing !
When you do this with Facebook Pixel, the price never display in log pixel.

Have you publish a video with the price with Pixel Facebook, in Youtube or in your blog ?

Thanks a lot !

    Julius
    • Jun 10 2020
    • Reply

    I don't have a video because I don't run a Youtube channel.

James Murphy
  • Jun 10 2020
  • Reply

Hi Julius:
Great articles - was curious how you do this since we just finished an ecommerce GTM implementation. We opted to use your option 3 approach to get price as a number.
For Soso using option 3 to obtain a number for your Facebook conversion may work for you as well.
Thanks for all the contributions!

Jok
  • Jun 11 2020
  • Reply

Hi Julius, thank you very much.

I'm just starting out with jscript and was curious if you maybe could explain the code in more detail?

F.e. this part:

var regex = /([0-9.,]+)/;
if (regex.test(priceText)) {
return priceText.match(regex)[0].replace(/,/g, '');
}

    Julius Fedorovicius
    • Jun 11 2020
    • Reply

    regex is the regular expression that extracts only numbers, commas and dots.
    Then I test whether the priceText matches regex. If yes, then I proceed with the extraction. I take the first match (its index is zero 0) and replace the commas with nothing (in other words, the commas are removed).

      Jok
      • Jun 11 2020
      • Reply

      Great! Thanks again!

sowpna
  • Nov 3 2024
  • Reply

value-perception_index variable how can create

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *


 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
Recent Posts
  • LinkedIn Conversions API with Google Tag Manager. The Guide.
  • How to Set Up Google Tag Manager Server-side Tagging with Cloud Run
  • Track HubSpot Forms with Google Tag Manager and Google Analytics 4
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings