使用结构化数据标记 javascript

Using structured data markup javascript

在结构化数据标记中,我想插入带有 java 的发布日期 script.is 有办法做到这一点吗?

示例模式;

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

我必须在页面上的时间标签内获取日期,并使用 javascript 将其放入架构中。

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

我删除了 datePublished 因为如果有 JS 变量它是无效的标记,我们应该完全使用 JS 添加它,即使 Javascript 被禁用也是有效的。

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

并添加 datePublished 你可以使用这个

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)