Reputation: 71
I am trying to capture the value of the "sku" as a variable in GTM. This value will change on every product page.
The code on page looks like this:
<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 variable expected to be captured: 305FS-UJNA5 (without double quotes).
Is there a way to accomplish this by using a custom javascript variable type that will search for "sku": "
on the page and return the value till the next double quote?
Or, what what would be the best way to accomplish this?
I've tried the search but returns undefined in GTM...
function () {
var content = document.body.innerText;
var query=""sku": "";
if (content.search(query) > -1 ) {
return true;
} else {
return false;
}
}
Upvotes: 0
Views: 3353
Reputation: 32760
If you are prepared to accept a hackish 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 loads the contents of the script-Tag into a variable called "json" and you can load that into a global js variable or push individual properties to the datalayer (i.e. in the example json.sku will hold the sku). If you do not do this on an existing event (e.g . Dom Ready) you will need to push a custom event to make GTM aware of the value.
Obviously you can put the script in a custom HTML tag (as long it is run after your script tag has rendered) if you cannot change the page code. This is just meant to be a working example.
This worked for me in Chrome, it is not tested with other browsers or tested for side effects so you'll probably need to expand on the idea, but it is doable (even if it looks ugly).
Actually this can be written slightly more concise:
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);
}
which selects only the script tags with the proper type attribute. And if you know for certain you have only one script tag you could use document.querySelector
instead of document.querySelectorAll
and dispense with the loop (since that would return a single result).
Upvotes: 1