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

241

我需要的信息在一个meta标签中。当property="video"时,我如何访问meta标签中"content"数据?

HTML:

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

5
请注意,<meta> 标签应该有一个 name 属性,而不是 property 属性。使用标准属性的开发者需要根据大多数答案提供的代码进行调整。 - Jens Bannmann
25个回答

367

其他答案可能已经解决了问题,但这个答案更简单,不需要使用 jQuery:

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

原始问题使用了一个带有property=""属性的RDFa标签。针对普通的HTML <meta name="" …>标签,您可以使用以下内容:

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

7
即使我的元标记在<head>标签中,document.head.querySelector返回了null,但是document.querySelector完美地工作了。 - Robin van Baalen
12
为了让OG标签正常工作,请像这样给它加上引号:var title = document.head.querySelector('[property="og:title"]'); - arpo
1
不错。 "[content]" 部分有什么作用?没有它,我也会得到元素。 - citykid
1
@citykid 看起来有点多余。如果“属性”未找到标签,则片段将始终引发TypeError。在选择器中包含[content]将该异常扩展到任何匹配标记缺少内容属性的情况。在我看来,在这种情况下获得空结果更有意义,但我想这取决于实现者的偏好。 - natevw
当未闭合的元素没有以“/”结尾时,例如在此网站上,meta标签视口<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0">没有使用“/”,因此document.querySelector(meta[property='viewport'])返回null。 - Biegacz

157
你可以使用这个:

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

6
你真正想要的是让它们局部定义,使用 'let' 关键字就可以实现这一点 ;) - tommed
44
如果你会使用querySelector,你可以像这样操作:document.querySelector("meta[property='og:url']").getAttribute('content') - user1267177
3
我认为这个答案不太相关,你应该真正使用https://dev59.com/y2sz5IYBdhLWcg3w_NAD#35649085 - Sergei Basharov
跳过此答案。在 OP 的(确实奇怪的)情况下,它不起作用,因为它查看“名称”而不是“属性”属性。而且,在当前状态下,它过于复杂,没有任何向后兼容性优势 - 任何支持 const/let 的浏览器都应该支持 .querySelector - natevw
2
为什么要循环多次只为一个元属性?它可能有数百个元标签,或者需要多次获取元值。 - S K R
1
为什么有人会每次循环遍历所有元数据?如果有数百个,那性能怎么办? - S K R

133

一句话简介

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

31

有一种更简单的方法:

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

这在至少IE11中有效,使其更有用。 - rprez
2
document.querySelector 版本可以在 IE8 上正常工作,所以它非常适用。 - fregante
这通常是一种相当不错的方式,但请注意 OP 正在使用 RDFa 的 "property" 属性而不是更基本的 "name" 属性 (https://dev59.com/v2Eh5IYBdhLWcg3wfjiq)。 - natevw

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

使用方式如下:

getMetaContentByName("video");

本页面上的示例:

getMetaContentByName("twitter:domain");

我使用了这个小技巧,但在某个页面上出现了“类型错误”,因为元标记本身丢失了。我通过分配一个变量并将document.queryselector包装在try语句中来解决这个问题,这样我就可以在出错的情况下默认获得"" - bgmCoder
function getMetaContentByName(name,content){ var content = (content==null)?'content':content; try{ return document.querySelector("meta[name='"+name+"']").getAttribute(content); }catch{ return null; } } - devMariusz

17

如果您使用jQuery,可以使用:

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

11
假设使用jQuery或其他库,而不是纯JavaScript。 - ILMostro_7

16

Jquery可以通过以下方式实现:

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

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

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

10
这似乎可以工作(至少在Chrome中):document.getElementsByTagName('meta')['video'].getAttribute('content'); 如果标记如下所示:<meta name="video" content="http://video.com/video33353.mp4" /> - samdeV
1
@samdeV,这是所有解决方案中最清晰的。把它作为你自己的答案提交吧。 :) - frandroid
1
@samdeV,另外你不需要使用.getAttribute('content'),你可以直接使用.content:document.getElementsByTagName('meta')['video'].content。我刚刚测试过,在Firefox中也能正常工作。 - frandroid
我现在得知它在Safari中不起作用。该死。 - frandroid

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

通过这种方式,您可以获取元标记的内容。


6

方式 - [ 1 ]

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

您可能会遇到以下错误: 未捕捉的类型错误:无法读取null的getAttribute属性。
方法 - [2]
function getMetaContent(name){
    return document.getElementsByTagName('meta')[name].getAttribute("content");
}
console.log(getMetaContent('csrf-token'));

您可能会遇到以下错误: Uncaught TypeError: Cannot read property 'getAttribute' of null
方法 - [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,这是好的。


太棒了,我只需要这段代码来获取 CSRF 令牌。 - ehsan wwe

5

很简单吧,对吧?

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接