Skip to content
Advertisement

Getting META description via jQuery

Let’s say I do a simple AJAX request (in jQuery) like geturl.php?url=http://google.com

and geturl.php is this:

<?php
    if($_GET['url'])
    {
        $url=$_GET['url'];
        echo file_get_contents($url);
    }
?>

Simple, right?

How would I grab the META description from the returned (really long) string in jQuery?

Here’s what I have so far. Yes, I know, desc is wrong.

$.get("geturl.php?url="+url,function(response)
{
    // Loading <title></title>data
    var title=(/<title>(.*?)</title>/m).exec(response)[1];
    var desc = $("meta[name=description]").val();
    $("#linkbox").html("<div><b>"+title+"</b><br/>"+url+"<br />Desc: " + desc)
});

Advertisement

Answer

Using regular expressions to parse HTML is bad practice.

Annoyingly, jQuery doesn’t support parsing elements in the head, only the body. So use straight JS instead:

window.onload = function(){ 
    $.ajax({
          type: 'GET', 
          url: '/',
          dataType: 'html',
          success: function(data) {

            //cross platform xml object creation from w3schools
            try //Internet Explorer
              {
              xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
              xmlDoc.async="false";
              xmlDoc.loadXML(data);
              }
            catch(e)
              {
              try // Firefox, Mozilla, Opera, etc.
                {
                parser=new DOMParser();
                xmlDoc=parser.parseFromString(data,"text/xml");
                }
              catch(e)
                {
                alert(e.message);
                return;
                }
              }

            var metas = xmlDoc.getElementsByTagName("meta");
            for (var i = 0; i < metas.length; i++) {
              if (metas[i].getAttribute("name") == "description") {
                alert(metas[i].getAttribute("content") || metas[i].getAttribute("edit"));
              }
            }
          }
    });
  }

Shamelessly ripped from David Burrows. Thanks, David!

fiddle: http://jsfiddle.net/wCL8W/8/

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement