program tip

JavaScript로 메타 태그에서 정보를 얻으려면 어떻게해야합니까?

radiobox 2020. 8. 6. 08:11
반응형

JavaScript로 메타 태그에서 정보를 얻으려면 어떻게해야합니까?


필요한 정보는 메타 태그에 있습니다. "content"메타 태그 데이터에 액세스하려면 어떻게 property="video"해야합니까?

HTML :

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

이것을 사용할 수 있습니다 :

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

다른 답변은 아마도 트릭을 수행해야하지만 이것은 더 간단하고 jQuery가 필요하지 않습니다.

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

여기에 답을 읽기가 어렵습니다. 하나의 라이너

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

더 쉬운 방법이 있습니다 :

document.getElementsByName('name of metatag')[0].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");

JQuery를 사용하는 경우 다음을 사용할 수 있습니다.

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

Jquery에서는 다음을 사용하여이를 달성 할 수 있습니다.

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

JavaScript에서는 다음을 사용하여이를 달성 할 수 있습니다.

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

- [ 1 ]

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

오류가 발생할 수 있습니다. 잡히지 않은 TypeError : null의 'getAttribute'속성을 읽을 수 없습니다


- [ 2 ]

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

오류가 발생할 수 있습니다. 잡히지 않은 TypeError : null의 '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'));

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


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/


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

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"

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

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.


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

참고URL : https://stackoverflow.com/questions/7524585/how-do-i-get-the-information-from-a-meta-tag-with-javascript

반응형