i have written a JS code to dynamically post a schema, the code is working on my computer and its working on firefox consol, sometimes its working on chrome console but its not working on Google Tag Manager, why?
i have checked the allow document.write check box and when i check the preview mode it shows the the tag is fired but the code inside the tag is plain, meaning its not executed, and when i submit and go check on live site, there is nothing! but i can still see the json code in the console
this is what is inside the HTML tag and the trigger is all pages (just to make sure)
How can i make this code work with GTM?
`
<script>
window.onload = function() {
var featured_div = document.getElementById("featured")
var bigTitle = document.getElementById("bigtitle1")
var items = featured_div.querySelectorAll(".lower")
var schema = {
"@context": "https://schema.org",
"@type": "Article",
"@id":window.location.href + "/#article",
"text" : "ash",
"about": {
"@context": "https://schema.org",
"@type": "Place",
"@id": "place",
"name": document.querySelector(".hero-titulo").innerText,
"image": " ",
"publicAccess": true,
"sameAs": [
"https://www.louvre.fr/en",
"https://en.wikipedia.org/wiki/Louvre"
],
"address": "Paris, France",
"additionalType": "Museum"
},
"mainEntityOfPage": {
"@context": "https://schema.org",
"@type": "WebPage",
"@id": window.location.href,
"mentions": {
"@context": "https://schema.org",
"@type": "ItemList",
"@id": "itemlist",
"name": document.querySelector(".bigtitle1").innerText,
"description": "Puedes caminar desde aquí hasta estas atracciones vecinas",
"itemListElement": [
]
}
}
}
for (var i =0; i<items.length;++i) {
var lower = items[i].querySelector("a")
var desc = items[i].querySelectorAll("p")
schema["mainEntityOfPage"]["mentions"]["itemListElement"][i]={
"@type": "ListItem",
"name":lower.innerText,
"url":lower.href,
"description":desc[1].innerText
} //end of listitem dictionary
} //end of for loop
var scrip = document.createElement('script')
scrip.type = 'application/ld+json'
scrip.id = 'schemantra'
scrip.innerHTML = JSON.stringify(schema)
document.body.appendChild(scrip)
}
</script>`
i tried the code offline, it works but with GTM it doesnt
If your GTM container or trigger is later than
window load
. I guess this code won't fire.You can remove the
window.onload = function() {}
on the outside. And make the GTM trigger towindow Loaded
.This might help