简体   繁体   中英

Using structured data markup javascript

In structured data markup, I want to insert publish date with java script.is there a way to do this?

example schema;

<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>

I have to take the date inside the time tag on the page and put it in the schema with javascript.

<time datetime="2021-02-24T12:11:00+03:00">2021-02-24T12:11:00+03:00</time>

I removed the datePublished because it's not valid markup if there are JS variables, we should add it completely using JS, this is valid even if Javascript is disabled.

<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>

and to add datePublished you can use this

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM