我需要的信息在一个元标签中。当属性=“视频”时,我如何访问元标签的“内容”数据?

HTML:

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

当前回答

我的函数变体:

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

其他回答

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

以这种方式使用:

getMetaContentByName("video");

本页上的例子:

getMetaContentByName("twitter:domain");

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

通过对函数进行包装,这也可以作为一行代码来完成。

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;
})();

路- [1]

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

你可能会得到错误: 无法读取属性“getAttribute”为空


路- [2]

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

你可能会得到错误: 无法读取属性“getAttribute”为空


路- [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'));

而不是得到error,得到null,这很好。

如果元标签是:

<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" />'

复杂网站和元数据的问题是元标签并不总是有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') );
      }
  }