You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript提取页面time标签日期插入结构化数据标记

完全可以实现,推荐直接通过JS构造schema对象后序列化插入页面,避免手动拼接JSON出现的语法错误,实现代码如下:

// 等待DOM加载完成再执行,避免获取不到time标签
document.addEventListener('DOMContentLoaded', function() {
  // 1. 获取time标签的datetime属性值
  const publishTimeEle = document.querySelector('time');
  // 如果有多个time标签,建议给目标time加id,比如id="article-publish-time",然后用下面的写法
  // const publishTimeEle = document.getElementById('article-publish-time');
  if (!publishTimeEle) return;
  const datePublished = publishTimeEle.getAttribute('datetime');

  // 2. 构造完整的schema对象
  const newsSchema = {
    "@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": datePublished,
    "author": [{
        "@type": "Person",
        "name": "Jane Doe",
        "url": "http://example.com/profile/janedoe123"
      },{
        "@type": "Person",
        "name": "John Doe",
        "url": "http://example.com/profile/johndoe123"
    }]
  };

  // 3. 创建application/ld+json的script标签,插入到页面头部
  const scriptEle = document.createElement('script');
  scriptEle.type = 'application/ld+json';
  scriptEle.textContent = JSON.stringify(newsSchema);
  document.head.appendChild(scriptEle);
});

注意事项

  • 不要直接修改页面上已有的静态ld+json脚本内容,搜索引擎爬虫可能不会执行JS读取修改后的值,动态插入的完整script标签是可以被正常识别的。
  • 如果你的页面内容是服务端渲染的,优先用服务端直接填充日期,性能和兼容性比前端JS注入更好。

内容的提问来源于stack exchange,提问作者awakening

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 09:27:06