En el marcado de datos estructurados, quiero insertar la fecha de publicación con java script. ¿Hay alguna forma de hacerlo?
esquema de ejemplo;
<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "NewsArticle", "headline": "Article headline", "image": [ "https://example.com/photos/1x1/photo.jpg", "https://example.com/photos/4x3/photo.jpg", "https://example.com/photos/16x9/photo.jpg" ], "datePublished": "+ date variable +", "author": [{ "@type": "Person", "name": "Jane Doe", "url": "http://example.com/profile/janedoe123" },{ "@type": "Person", "name": "John Doe", "url": "http://example.com/profile/johndoe123" }] } </script>Tengo que tomar la fecha dentro de la etiqueta de tiempo en la página y ponerla en el esquema con javascript.
<time datetime="2021-02-24T12:11:00+03:00">2021-02-24T12:11:00+03:00</time>datePublished la fecha de publicación porque no es un marcado válido si hay variables JS, debemos agregarlo completamente usando JS, esto es válido incluso si Javascript está deshabilitado.
<script id='structured-data' type="application/ld+json"> { "@context": "https://schema.org", "@type": "NewsArticle", "headline": "Article headline", "image": ["https://example.com/photos/1x1/photo.jpg", "https://example.com/photos/4x3/photo.jpg", "https://example.com/photos/16x9/photo.jpg"], "author": [{ "@type": "Person", "name": "Jane Doe", "url": "http://example.com/profile/janedoe123" },{ "@type": "Person", "name": "John Doe", "url": "http://example.com/profile/johndoe123" }] } </script> y para agregar datePublished puedes usar esto
let timeValue = document.querySelector('time').dateTime; let structuredData = document.getElementById('structured-data'); let parsedSD = JSON.parse(structuredData.innerText); parsedSD.datePublished = timeValue; structuredData.innerText = JSON.stringify(parsedSD)