Made a few attempts to insert the structured data stored from an Airtable field (SEO:JSON-LD) into the of the page. While the console.log displays the structured data correctly, it does not actually appear within the .
The line document.head.appendChild(jsonldScript);
seems to be failing. Thoughts anyone?
<script>
document.addEventListener("DOMContentLoaded", function() {
var waitForData = setInterval(function () {
if (typeof $ != 'undefined') {
const recordId = getUrlParam('recordId');
if (window.records && window.records[recordId] && window.records[recordId].record.fields['SEO:JSON-LD']) {
const jsonldScript = document.createElement('script');
jsonldScript.setAttribute('type', 'application/ld+json');
const structuredData = window.records[recordId].record.fields['SEO:JSON-LD'];
jsonldScript.textContent = structuredData;
console.log(jsonldScript);
document.head.appendChild(jsonldScript);
clearInterval(waitForData);
}
}
}, 100);
function getUrlParam(name) {
const url = new URL(window.location.href);
let param;
for(var key of url.searchParams.keys()) {
if(key.toLowerCase() === name.toLowerCase()) {
param = url.searchParams.get(name);
break;
}
}
if(!param && name.toLowerCase() === 'recordid') {
param = getRecordIdFromPath();
}
return param;
}
function getRecordIdFromPath() {
let pathName = window.location.pathname;
if (pathName.indexOf('/r/rec') !== -1) {
pathName = pathName.substr(pathName.indexOf('/r/rec') + 3);
if (pathName.indexOf("/") !== -1) {
pathName = pathName(0, pathName.indexOf('/'))
}
return pathName;
}
return undefined;
}
});
</script>
From the console: