How to get meta tag information from an external url?

1

I need to get the meta tag of a specific external url, however I found only examples using jquery to perform this functionality, not pure javascript. In pure js, I found this post where I accomplished 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 "";
} 

link

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

    
asked by anonymous 14.06.2016 / 15:19

2 answers

1

Because of the CORS (Cross-Origin Resource Sharing) restriction, read about here ) , browsers block requests by default out of your domain.

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

In the code below I make a forward request, I get the return that will be the HTML of the page, a function receives the return and does all necessary processing, I made a parse of 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>
    
14.06.2016 / 16:42
-1

You can order normally as you would any internal address. Then just create the crossdomain.xml file at the root of your site.

See here a crossdomain question. xml already resolved.

For a complete reference see the Adobe website link

    
15.06.2016 / 19:41