How to get meta tag information from an external url?

Asked

Viewed 574 times

3

I need to get the meta tag from a specific external url, but I only found examples using jquery to perform this feature, not pure javascript. In pure js, I found this post where is performed what I need, but not on any external page, but on the page itself.

function getVideoContent() { 
   var metas = document.getElementsByTagName('meta'); 

   for (var i=0; i<metas.length; i++) { 
      if (metas[i].getAttribute("property") == "video") { 
         return metas[i].getAttribute("content"); 
      } 
   } 

    return "";
} 

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

Does anyone know how I can get meta tag information from any url using pure javascript only?

2 answers

3


Due to CORS restriction (Cross-Origin Resource Sharing, read about here), browsers block by default requests outside your domain.

But we can use a proxy like crossorigin.me to perform this type of request.

In the code below I perform a proxiated request, I get the return that will be the HTML of the page, a function receives the return and does all the necessary processing, I parsed the string for DOM elements, I used a part of the code of your question to retrieve a specific tag and display it in a div.

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'https://crossorigin.me/http://example.com/');
xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == XMLHttpRequest.DONE) {
    if (xmlhttp.status == 200) {
      tratativa(xmlhttp.responseText);
    } else {
      console.log('Error: ' + xmlhttp.statusText)
    }
  }
}
xmlhttp.send();

function tratativa(htmlString) {
  var parser = new DOMParser();
  var documentoBody = parser.parseFromString(htmlString, "text/html");

  var metaTags = documentoBody.getElementsByTagName('meta');

  for (var i = 0; i < metaTags.length; i++) {
    if (metaTags[i].getAttribute("name") == "viewport") {
      document.getElementById("retorno").innerHTML = metaTags[i].getAttribute("content");
    }
  }
}
<div id="retorno"></div>

-1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.