如何使用JavaScript动态更新元标签(OG)

问题描述 投票:0回答:2

这是我在 Stack 社区中提出的第一个问题。我知道之前已经有人问过这个问题,但我想知道如何使用 JS 来具体实现它(我不是受过教育的编码员)。

这是我正在尝试做的事情:

var pageTitle = document.getElementsByTagName('h1');
document.getElementById("demo").innerHTML = pageTitle[0].innerHTML;
<html>
<head>
<title>Update meta tag dynamically</title>
<meta property="og:title" content="id=demo"/>
</head>
    <body>
        <h1>First header</h1>
    </body>
</html>

我知道这不是如何使用标签,只是为了向您展示我想做什么。

PS:我们不能在后端运行任何东西,所以它必须在 代码。

这是我发现的其他东西,但它也不起作用:

<meta name="description" content="Old">
<h1>New</h1>
<script type='text/javascript'>
$(document).ready(function() {
    var metaTitle = document.getElementsByTagName('h1');
    // Just replacing the value of the 'content' attribute will not work.
    $('meta[name=description]').remove();
    $('head').append( '<meta name="description" content"$metaTitle">' );
});
</script> 
javascript metadata facebook-opengraph meta
2个回答
0
投票

动态更改

og
属性

    <head>
        <meta property="og:title" content="" />
        <meta property="og:url" content="" />
        <meta property="og:image" content="" />
        <meta property="og:type" content="article" />
        <meta property="og:description" content="" />
    </head>
    const metas = Array.from(document.getElementsByTagName('meta'))
    const metaTitle = metas.find((m) => m.attributes[0].nodeValue === 'og:title')
    metaTitle.attributes[1].nodeValue = 'a title'
    const metaUrl = metas.find((m) => m.attributes[0].nodeValue === 'og:url')
    metaUrl.attributes[1].nodeValue = window.location.href
    const metaImage = metas.find((m) => m.attributes[0].nodeValue === 'og:image')
    metaImage.attributes[1].nodeValue = 'a image'
    const metaDescription = metas.find((m) => m.attributes[0].nodeValue === 'og:description')
    metaDescription.attributes[1].nodeValue = 'a description'

-2
投票

终于破解了密码。这是给未来的流浪者的:https://github.com/idaljot/meta-tag-auto-update/blob/master/meta-tag.htm

© www.soinside.com 2019 - 2024. All rights reserved.