如何使用 JavaScript 从元标记获取信息?

发布于 2024-12-05 19:57:05 字数 221 浏览 5 评论 0原文

我需要的信息位于元标记中。当 property="video" 时,如何访问元标记的 "content" 数据?

HTML:

<meta property="video" content="http://video.com/video33353.mp4" />

The information I need is in a meta tag. How can I access the "content" data of the meta tag when property="video"?

HTML:

<meta property="video" content="http://video.com/video33353.mp4" />

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

沒落の蓅哖 2024-12-12 19:57:06

我的函数变体:

const getMetaValue = (name) => {
  const element = document.querySelector(`meta[name="${name}"]`)
  return element?.getAttribute('content')
}

My variant of the function:

const getMetaValue = (name) => {
  const element = document.querySelector(`meta[name="${name}"]`)
  return element?.getAttribute('content')
}
独守阴晴ぅ圆缺 2024-12-12 19:57:06

这段代码适用于我

<meta name="text" property="text" content="This is text" />
<meta name="video" property="text" content="http://video.com/video33353.mp4" />

JS

var x = document.getElementsByTagName("META");
    var txt = "";
    var i;
    for (i = 0; i < x.length; i++) {
        if (x[i].name=="video")
        {
             alert(x[i].content);
         }

    }    

示例小提琴: http://jsfiddle.net/muthupandiant/ogfLwdwt/

This code works for me

<meta name="text" property="text" content="This is text" />
<meta name="video" property="text" content="http://video.com/video33353.mp4" />

JS

var x = document.getElementsByTagName("META");
    var txt = "";
    var i;
    for (i = 0; i < x.length; i++) {
        if (x[i].name=="video")
        {
             alert(x[i].content);
         }

    }    

Example fiddle: http://jsfiddle.net/muthupandiant/ogfLwdwt/

手长情犹 2024-12-12 19:57:06

这是一个函数,它将返回任何元标记的内容并记住结果,避免不必要的 DOM 查询。

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            var theMetaContent, wasDOMQueried = true;;
            if (metas[metaName]) {
                theMetaContent = metas[metaName];
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) {
                    if (el.name === metaName) theMetaContent = el.content;
                    metas[metaName] = theMetaContent;
                });
            }
            console.log("Q:wasDOMQueried? A:" + wasDOMQueried);
            return theMetaContent;
        }
        return metaGetter;
    })();

getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM  was only queried once */

这是一个扩展版本,它还查询 开放图标记,并使用 Array#some

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            wasDOMQueried = true;
            if (metas[metaName]) {
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) {
                        if(el.name === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        if(el.getAttribute("property") === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        else{
                          metas[metaName] = "meta tag not found";
                        }  
                    });
            }
            console.info("Q:wasDOMQueried? A:" + wasDOMQueried);
            console.info(metas);
            return metas[metaName];
        }
        return metaGetter;
    })();

getMetaContent("video"); // "http://video.com/video33353.mp4"

Here's a function that will return the content of any meta tag and will memoize the result, avoiding unnecessary querying of the DOM.

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            var theMetaContent, wasDOMQueried = true;;
            if (metas[metaName]) {
                theMetaContent = metas[metaName];
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.forEach.call(document.getElementsByTagName("meta"), function(el) {
                    if (el.name === metaName) theMetaContent = el.content;
                    metas[metaName] = theMetaContent;
                });
            }
            console.log("Q:wasDOMQueried? A:" + wasDOMQueried);
            return theMetaContent;
        }
        return metaGetter;
    })();

getMetaContent("description"); /* getMetaContent console.logs the content of the description metatag. If invoked a second time it confirms that the DOM  was only queried once */

And here's an extended version that also queries for open graph tags, and uses Array#some:

var getMetaContent = (function(){
        var metas = {};
        var metaGetter = function(metaName){
            wasDOMQueried = true;
            if (metas[metaName]) {
                wasDOMQueried = false;
            }
            else {
                 Array.prototype.some.call(document.getElementsByTagName("meta"), function(el) {
                        if(el.name === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        if(el.getAttribute("property") === metaName){
                           metas[metaName] = el.content;
                           return true;
                        }
                        else{
                          metas[metaName] = "meta tag not found";
                        }  
                    });
            }
            console.info("Q:wasDOMQueried? A:" + wasDOMQueried);
            console.info(metas);
            return metas[metaName];
        }
        return metaGetter;
    })();

getMetaContent("video"); // "http://video.com/video33353.mp4"
北恋 2024-12-12 19:57:06
function getDescription() {
    var info = document.getElementsByTagName('meta');
    return [].filter.call(info, function (val) {
        if(val.name === 'description') return val;
    })[0].content;
}

更新版本:

function getDesc() {
    var desc = document.head.querySelector('meta[name=description]');
    return desc ? desc.content : undefined;
}
function getDescription() {
    var info = document.getElementsByTagName('meta');
    return [].filter.call(info, function (val) {
        if(val.name === 'description') return val;
    })[0].content;
}

update version:

function getDesc() {
    var desc = document.head.querySelector('meta[name=description]');
    return desc ? desc.content : undefined;
}
困倦 2024-12-12 19:57:06

将所有元值复制到缓存对象:

/* <meta name="video" content="some-video"> */

const meta = Array.from(document.querySelectorAll('meta[name]')).reduce((acc, meta) => (
  Object.assign(acc, { [meta.name]: meta.content })), {});

console.log(meta.video);

copy all meta values to a cache-object:

/* <meta name="video" content="some-video"> */

const meta = Array.from(document.querySelectorAll('meta[name]')).reduce((acc, meta) => (
  Object.assign(acc, { [meta.name]: meta.content })), {});

console.log(meta.video);
昇り龍 2024-12-12 19:57:06

我们可以使用直接一行

来获取元描述或关键字或头部分中的任何元标记,如以下代码所示:

document.head.getElementsByTagName('meta')['description'].getAttribute('content');

只需将 ['description'] 更改为关键字或元名称 rang 的元素

这是一个示例:
使用 document.head 获取元名称值

The simple way preferred

We can use direct one line to get meta description or keyword or any meta tag in head section as this code:

document.head.getElementsByTagName('meta')['description'].getAttribute('content');

Just change ['description'] to keywords or element of meta name rang

This is an example:
using document.head to get meta names values

夏の忆 2024-12-12 19:57:06

如果您对获取所有元标记的更深远的解决方案感兴趣,您可以使用这段代码

function getAllMetas() {
    var metas = document.getElementsByTagName('meta');
    var summary = [];
    Array.from(metas)
        .forEach((meta) => {
            var tempsum = {};
            var attributes = meta.getAttributeNames();
            attributes.forEach(function(attribute) {
                tempsum[attribute] = meta.getAttribute(attribute);
            });
            summary.push(tempsum);
        });
    return summary;
}

// usage
console.log(getAllMetas());

If you are interessted in a more far-reaching solution to get all meta tags you could use this piece of code

function getAllMetas() {
    var metas = document.getElementsByTagName('meta');
    var summary = [];
    Array.from(metas)
        .forEach((meta) => {
            var tempsum = {};
            var attributes = meta.getAttributeNames();
            attributes.forEach(function(attribute) {
                tempsum[attribute] = meta.getAttribute(attribute);
            });
            summary.push(tempsum);
        });
    return summary;
}

// usage
console.log(getAllMetas());
过气美图社 2024-12-12 19:57:06

我个人更喜欢将它们放入一个对象哈希中,然后我可以在任何地方访问它们。这可以很容易地设置为可注入变量,然后所有东西都可以拥有它,并且只抓取一次。

通过包装函数,这也可以作为一个衬垫来完成。

var meta = (function () {
    var m = document.querySelectorAll("meta"), r = {};
    for (var i = 0; i < m.length; i += 1) {
        r[m[i].getAttribute("name")] = m[i].getAttribute("content")
    }
    return r;
})();

I personally prefer to just get them in one object hash, then I can access them anywhere. This could easily be set to an injectable variable and then everything could have it and it only grabbed once.

By wrapping the function this can also be done as a one liner.

var meta = (function () {
    var m = document.querySelectorAll("meta"), r = {};
    for (var i = 0; i < m.length; i += 1) {
        r[m[i].getAttribute("name")] = m[i].getAttribute("content")
    }
    return r;
})();
花心好男孩 2024-12-12 19:57:06

仅供参考,根据 https://developer.mozilla.org/en -US/docs/Web/HTML/Element/meta 全局属性有效,这意味着 id 属性可以与 getElementById 一起使用>。

FYI according to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta global attributes are valid which means the id attribute can be used with getElementById.

酸甜透明夹心 2024-12-12 19:57:06

使用 meta root 然后获取和设置其任何属性:

let meta = document.getElementsByTagName('meta')

console.log(meta.video.content)
> "http://video.com/video33353.mp4"

meta.video.content = "https://www.example.com/newlink"

Using meta root and then getting and setting any of its properties:

let meta = document.getElementsByTagName('meta')

console.log(meta.video.content)
> "http://video.com/video33353.mp4"

meta.video.content = "https://www.example.com/newlink"
神魇的王 2024-12-12 19:57:06

复杂网站和元数据的问题在于元标记并不总是具有 itemprop 属性。在某些情况下,它们仅具有 itemprop 属性,但没有 name 属性。

使用此脚本,您可以获取所有具有 itemprop 属性的元并打印其内容。

  const allMeta = document.getElementsByTagName("meta");
    
  for (let i = 0; i < allMeta .length; i++) {
      if( allMeta [i].getAttribute("itemprop") != null){
        console.log( allMeta [i].getAttribute("itemprop")+":"+allMeta [i].getAttribute('content') );
      }
  }

The problem with complex websites and metadata is that meta tags not always have the itemprop attribute. And in some case they have itemprop only but not a name attribute.

With this script you can get all the Meta with an itemprop attribute and print its content.

  const allMeta = document.getElementsByTagName("meta");
    
  for (let i = 0; i < allMeta .length; i++) {
      if( allMeta [i].getAttribute("itemprop") != null){
        console.log( allMeta [i].getAttribute("itemprop")+":"+allMeta [i].getAttribute('content') );
      }
  }
生寂 2024-12-12 19:57:06

使用 vanilla-js 非常简单......

var author = document.querySelector("meta[name=author]").content;
alert(`My author is ${author}`);

It's very simple with vanilla-js...

var author = document.querySelector("meta[name=author]").content;
alert(`My author is ${author}`);
好久不见√ 2024-12-12 19:57:06
<html>
<head>
<meta property="video" content="http://video.com/video33353.mp4" />
<meta name="video" content="http://video.com/video33353.mp4" />
</head>
<body>

<script>
var meta = document.getElementsByTagName("meta");
    size = meta.length;

for(var i=0; i<size; i++) {
    if (meta[i].getAttribute("property") === "video") {
        alert(meta[i].getAttribute("content"));
    }
}
meta = document.getElementsByTagName("meta")["video"].getAttribute("content");
alert(meta);
</script>
</body>
</html>

演示

<html>
<head>
<meta property="video" content="http://video.com/video33353.mp4" />
<meta name="video" content="http://video.com/video33353.mp4" />
</head>
<body>

<script>
var meta = document.getElementsByTagName("meta");
    size = meta.length;

for(var i=0; i<size; i++) {
    if (meta[i].getAttribute("property") === "video") {
        alert(meta[i].getAttribute("content"));
    }
}
meta = document.getElementsByTagName("meta")["video"].getAttribute("content");
alert(meta);
</script>
</body>
</html>

Demo

享受孤独 2024-12-12 19:57:06

document.head.querySelector('meta[property=video]').content;

document.head.querySelector('meta[property=video]').content;

生活了然无味 2024-12-12 19:57:06

如果元标记是:

<meta name="url" content="www.google.com" />

JQuery 将是:

const url = $('meta[name="url"]').attr('content'); // url = 'www.google.com'

JavaScript 将是:(它将返回整个 HTML)

const metaHtml = document.getElementsByTagName('meta').url // metaHtml = '<meta name="url" content="www.google.com" />'

if the meta tag is:

<meta name="url" content="www.google.com" />

JQuery will be:

const url = $('meta[name="url"]').attr('content'); // url = 'www.google.com'

JavaScript will be: (It will return whole HTML)

const metaHtml = document.getElementsByTagName('meta').url // metaHtml = '<meta name="url" content="www.google.com" />'
终陌 2024-12-12 19:57:05

其他答案可能应该可以解决问题,但是这个更简单并且不需要 jQuery:

document.head.querySelector("[property~=video][content]").content;

最初的问题使用了 带有 property="" 属性的 RDFa 标记。对于普通的 HTML 标签,您可以使用如下内容:

document.querySelector('meta[name="description"]').content

The other answers should probably do the trick, but this one is simpler and does not require jQuery:

document.head.querySelector("[property~=video][content]").content;

The original question used an RDFa tag with a property="" attribute. For the normal HTML <meta name="" …> tags you could use something like:

document.querySelector('meta[name="description"]').content
锦上情书 2024-12-12 19:57:05

你可以使用这个:

function getMeta(metaName) {
  const metas = document.getElementsByTagName('meta');

  for (let i = 0; i < metas.length; i++) {
    if (metas[i].getAttribute('name') === metaName) {
      return metas[i].getAttribute('content');
    }
  }

  return '';
}

console.log(getMeta('video'));

You can use this:

function getMeta(metaName) {
  const metas = document.getElementsByTagName('meta');

  for (let i = 0; i < metas.length; i++) {
    if (metas[i].getAttribute('name') === metaName) {
      return metas[i].getAttribute('content');
    }
  }

  return '';
}

console.log(getMeta('video'));
风透绣罗衣 2024-12-12 19:57:05

这里有一艘班轮

document.querySelector("meta[property='og:image']").getAttribute("content");

One liner here

document.querySelector("meta[property='og:image']").getAttribute("content");
情释 2024-12-12 19:57:05

有一个更简单的方法:

document.getElementsByName('name of metatag')[0].getAttribute('content')

There is an easier way:

document.getElementsByName('name of metatag')[0].getAttribute('content')
め七分饶幸 2024-12-12 19:57:05
function getMetaContentByName(name,content){
   var content = (content==null)?'content':content;
   return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}

使用方式:

getMetaContentByName("video");

本页示例:

getMetaContentByName("twitter:domain");
function getMetaContentByName(name,content){
   var content = (content==null)?'content':content;
   return document.querySelector("meta[name='"+name+"']").getAttribute(content);
}

Used in this way:

getMetaContentByName("video");

The example on this page:

getMetaContentByName("twitter:domain");
冬天旳寂寞 2024-12-12 19:57:05

如果您使用 JQuery,则可以使用:

$("meta[property='video']").attr('content');

If you use JQuery, you can use:

$("meta[property='video']").attr('content');
对你而言 2024-12-12 19:57:05

在 Jquery 中,您可以通过以下方式实现此目的:

$("meta[property='video']");

在 JavaScript 中,您可以通过以下方式实现此目的:

document.getElementsByTagName('meta').item(property='video');

In Jquery you can achieve this with:

$("meta[property='video']");

In JavaScript you can achieve this with:

document.getElementsByTagName('meta').item(property='video');
心作怪 2024-12-12 19:57:05
document.querySelector('meta[property="video"]').content

这样你就可以获得元的内容。

document.querySelector('meta[property="video"]').content

this way you can get the content of the meta.

×纯※雪 2024-12-12 19:57:05

方式 - [ 1 ]

function getMetaContent(property, name){
    return document.head.querySelector("["+property+"="+name+"]").content;
}
console.log(getMetaContent('name', 'csrf-token'));

您可能会收到错误:
未捕获的 TypeError: Cannot read property 'getAttribute' of null


Way - [ 2 ]

function getMetaContent(name){
    return document.getElementsByTagName('meta')[name].getAttribute("content");
}
console.log(getMetaContent('csrf-token'));

您可能会收到错误:
Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 3 ]

function getMetaContent(name){
    name = document.getElementsByTagName('meta')[name];
    if(name != undefined){
        name = name.getAttribute("content");
        if(name != undefined){
            return name;
        }
    }
    return null;
}
console.log(getMetaContent('csrf-token'));

相反,会出现错误,您会得到 null,那就好。

Way - [ 1 ]

function getMetaContent(property, name){
    return document.head.querySelector("["+property+"="+name+"]").content;
}
console.log(getMetaContent('name', 'csrf-token'));

You may get error:
Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 2 ]

function getMetaContent(name){
    return document.getElementsByTagName('meta')[name].getAttribute("content");
}
console.log(getMetaContent('csrf-token'));

You may get error:
Uncaught TypeError: Cannot read property 'getAttribute' of null


Way - [ 3 ]

function getMetaContent(name){
    name = document.getElementsByTagName('meta')[name];
    if(name != undefined){
        name = name.getAttribute("content");
        if(name != undefined){
            return name;
        }
    }
    return null;
}
console.log(getMetaContent('csrf-token'));

Instead getting error, you get null, that is good.

恬淡成诗 2024-12-12 19:57:05

简单的一个,对吧?

document.head.querySelector("meta[property=video]").content

Simple one, right?

document.head.querySelector("meta[property=video]").content
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文