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

如何用JavaScript将页面特定内容插入meta标签?

动态修改页面Meta标签实现SEO优化

要实现从页面动态抓取内容替换title和meta描述,只需把你写的静态内容换成动态获取的元素文本即可,具体实现如下:

完整代码

// 等待DOM加载完成再执行,避免元素未渲染导致获取失败
document.addEventListener('DOMContentLoaded', function() {
    // 替换title:获取h1的文本内容
    const pageTitle = document.querySelector('h1').textContent.trim();
    document.title = pageTitle;

    // 替换meta description:获取.intro的文本内容,清理多余空白
    const introText = document.querySelector('.intro').textContent.trim().replace(/\s+/g, ' ');
    const metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc) {
        metaDesc.content = introText;
    }
});

代码说明

  • document.querySelector('h1'):精准定位页面中的<h1>元素,通过textContent提取纯文本,trim()去除首尾多余的空格和换行。
  • document.querySelector('.intro'):获取class为intro的元素,提取文本后用replace(/\s+/g, ' ')把连续的空格、换行替换成单个空格,避免描述内容出现杂乱空白。
  • DOMContentLoaded事件监听:确保页面DOM元素全部渲染完成后再执行代码,防止因元素未加载导致的获取失败问题。
  • if (metaDesc)判断:避免页面不存在description标签时出现报错。

修改后效果

<head>
<title>Post Title</title>
<meta name="description" content="Intro text goes here">
</head>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:07:23