Obtain a specific text value as a variable using Google Tag Manager

In my quest to extract the dynamic "sku" value from GTM, I am faced with a challenge. This particular value is unique for each product page.

Below is an example of how the code appears on the page:

<script type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "Product",
  "sku": "305FS-UJNA5",
  "offers": [{
        "@type": "Offer",
        "price": "99.00",
        "availability": "InStock",
        "priceCurrency": "USD"
        }]
}
</script>

The goal is to capture the variable: 305FS-UJNA5 (without quotes).

One approach I've considered is using a custom JavaScript variable in GTM that can search for "sku": " within the page and retrieve the value up to the next double quote.

If this method proves difficult, what alternative would you suggest?

My attempts at searching have so far yielded undefined results within GTM...

function () {
var content = document.body.innerText;
var query=""sku": "";
if (content.search(query) > -1 ) {
    return true;
} else {
    return false;
    }
}

Answer №1

If you're open to considering a workaround solution

      <html>
        <head>
            <title></title>
                <script type="application/ld+json">
        {
          "@context": "http://schema.org",
          "@type": "Product",
          "sku": "305FS-UJNA5",
          "offers": [{
                "@type": "Offer",
                "price": "99.00",
                "availability": "InStock",
                "priceCurrency": "USD"
                }]
        }
        </script>
        </head>
        <body>
            <script>    
            json = {};
                scripts = document.getElementsByTagName('script');
                for (i = 0; i < scripts.length; ++i) {
                  script = scripts[i];
                  if(script.getAttribute('type') != "application/ld+json") {
                      continue;
                  }
                  json = JSON.parse(script.childNodes[0].nodeValue);
                  datalayer.push({ // dl must be initialized before
                    'event':'skuCapture',
                     'sku': json.sku
                  });
                }


            </script>
        </body>
        </html>

This will store the script-Tag content in a variable named "json," allowing you to access and manipulate it globally or push specific properties to the datalayer (e.g., json.sku holds the sku in this example). If you execute this outside of an existing event (like Dom Ready), you may need to trigger a custom event to inform GTM about the value.

If you can't modify the page code, you could embed this script inside a custom HTML tag as long as it runs after your initial script tag has loaded. This is just a functional demonstration.

I've tested this in Chrome, but its compatibility with other browsers and potential side effects remain unverified, so further testing and refinement may be necessary. Despite its slightly messy appearance, it's achievable.

A more concise version could look like:

var scripts = document.querySelectorAll("[type='application/ld+json']");
    for (i = 0; i < scripts.length; ++i) {
      script = scripts[i];
      json = JSON.parse(script.childNodes[0].nodeValue);
      console.log(json.sku);
    }  

This code targets only script tags with the correct type attribute. If you know there is only one script tag, consider using document.querySelector instead of document.querySelectorAll to avoid looping through results.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in refreshing JWPlayer page: Plugin loading failure - File not located

I'm implementing JWPlayer on my Localhost environment. Here's the code snippet I'm using: <div id="Player">loading...</div> <script type="text/javascript"> jwplayer("Player").setup({ file: "<?php echo $video[' ...

The issue where all buttons in a list are displaying the same ID

I am facing an issue with a row of buttons, all having the same class add-btn. Whenever I click on one button, I intend to log the id of its containing span. However, currently, all buttons are logging the span id of the first add-btn in the list. $(&apos ...

Connect the attributes of one object to the properties of another object

I am looking to create a new object in Javascript and assign its property some values from another object. I want this assignment to be like 'pass by reference' in C++. In the code snippet below: var object1 = { 'obj1' : { &ap ...

Coordinates of HTML elements corners after rotation

Seeking to obtain the XY coordinates of an HTML element in order to accurately calculate the physical distance, in pixels, from the corners of a rotated element relative to another element. In this code snippet, I am attempting to determine the distance f ...

The issue of nested tabs in Bootstrap 3 causing problems with sliders within the main tab has

Hello, I am utilizing Bootstrap 3 tabs. Within the nav-tabs, there are three tab-panes: the first tab contains text only, the second tab includes a slider, and the third tab has nested tabs. However, I encountered an issue where the slider in the nested t ...

Prevent pinch zoom in webkit (or electron)

Is there a way to prevent pinch zoom in an electron app? I've tried different methods, such as using event.preventDefault() on touchmove/mousemove events in JavaScript, adding meta viewport tags in HTML, adjusting -webkit-text-size-adjust in CSS, and ...

Wavy CSS Animation

For assistance with my spinning image, please check out this fiddle: https://jsfiddle.net/dricardo1/9a8p6srb/ Hello! I'm struggling with a spinning image that has a noticeable wobble when rotating. I can't seem to find a solution to make the rot ...

Building a table using a JSON object in a React component

I have been dynamically creating a table in React based on the API response received. data = {"name":"tom", "age":23, "group":null, "phone":xxx} Everything was working fine until I encountered a scenario w ...

How can I utilize Axios in Vue.js to access a local JSON file?

I'm trying to figure out how to read a local JSON file using Axios. The data.json file is located in public/info/data.json. However, every time I attempt to make a get request, I receive a 404 error message. Here is the content of data.json: [ {" ...

Tips for marking a textarea as mandatory when a choice is made

I'm creating an .html document for conducting a complete system check and confirming various aspects of its functionality. In this page, there is a table within a form structure where each row represents a step in the system verification process (e.g. ...

JQuery does not allow for changing the selection of a RadioButtonFor

I am currently working on a code that determines whether or not to display contact information. To achieve this, I am using the RadioButtonFor html-helper with a boolean value for the MVC view model in Razor. Upon loading the page, I need to switch from t ...

Unable to find the module... designated for one of my packages

Within my codebase, I am utilizing a specific NPM package called my-dependency-package, which contains the module lib/utils/list-utils. Moreover, I have another package named my-package that relies on my-dependency-package. When attempting to build the pr ...

The class name is not defined for a certain child element in the icon creation function

Currently, I am developing a Vue2 web application using Leaflet and marker-cluster. I am encountering an issue with the iconCreateFunction option in my template: <v-marker-cluster :options="{ iconCreateFunction: iconCreateClsPrg}"> ...

Replicate and $(document).ready()

My form has required fields that need to be completed. To alert users about blank fields, I have implemented the following code: $(document).ready(function() { $('input.required:text').focus(function() { $(this).css({'background ...

Refresh cloned element after making changes to the original element

Just starting to explore Jquery and looking for some guidance to get me started :) Question: I'm facing an issue with a cart total price that is displayed in a different part of the page using clone(). I want this cloned price to automatically update ...

Ways to manually trigger a reevaluation of Vuelidate validation

Is there a way to trigger Vuelidate to re-check a validation? For example, I have a form field where users can input the name of a remote directory. There is a Vuelidate validation in place that communicates with the server to verify if the directory exis ...

The current status of an ASP.Net Mvc Ajax request

Currently, I am utilizing @Ajax.ActionLink to invoke a controller action in an ajax manner. Is there a method to identify if there is already an ongoing/pending ajax request on the page? The desired functionality is simple: when a user clicks the link, the ...

How to maintain row highlight in jQuery datatable even after it is reloaded

I have a datatable set to reload every 10 seconds. When a user clicks on a row, it highlights, but the highlight is lost when the table reloads. Here is a condensed version of my datatable code: $(document).ready(function() { // set up datatable $(& ...

Prevent certain dates from being selected in a designated input field

I am facing an issue with disabling certain array dates for a specific input field in a datepicker calendar. Even though I have included the script to exclude those dates, they are not getting disabled for that particular input field. html <input cla ...

Learn how to cycle through three different texts that appear in the same spot using smooth transitions

I am working with three different rows that contain the Typography component. My goal is to display the first row, followed by the second, then the third, and back to the first one in a continuous loop. All three rows should be shown in the same location, ...