JSFiddle - React, Tailwind, and code Playground

by Kato Richardson

HTML

<h1>Results:</h1>
<div id="log"></div>

CSS

h3 { background-color: #ffc; }

p { color: #999; }

JavaScript

// given an html response, extract the title
function getTitle(data) {
    var matches = data.match(/<title>(.+)<\/title>/);
    return matches.length > 1? matches[1] : '';
}

// find the body tag of an element
// because browsers parse the innerHtml differently
// (http://stackoverflow.com/questions/2488839/does-jquery-strip-some-html-elements-from-a-string-when-using-html)
// we can't rely on just $(data) to do this right
function getBody(data) {
   var matches = data.match(/<body>(.+)<\/body>/);
   return $(matches[1]);
}

//given an html respones, extract a description
function getDesc(data) {
    var $data = $(data);
    var $match = $data.find('meta[name=description]');
    if ($match.length) {
        return $match.attr('content');
    }
    var $body = getBody(data);
    return $body.text().substring(0, 255).replace(/\n/, ' ');
}

// this url would point to a proxy (PHP) script on your server
// which would do a curl or similar operation to retrieve the
// url's contents; we just point to fiddle's simulator here
$.ajax('/echo/html/', {
    data: {
        // here you would pass the url you want to load to your
        // proxy script so it can fetch it; we're just cheating here
        // by using fiddle's response mechanism
        html: "<html><head><title>The Title</title><meta name='description' content='This is a hello world script' /></head><body><div>Hello World!</div></body></html>",
        delay: 1
    },
    success: function(data, status, xhr) {
        //console.log(data);
        //console.log(status);
        //console.log(xhr);
        
         $('#log').append('<h3>'+status+'</h3>')
            .append('<p>title='+getTitle(data)+'</h4>')
            .append('<p>desc='+getDesc(data)+'</p>');
    },
    type: 'POST',
    error: function(xhr, status, err) {
        $('#log').append('<h3>' + status + '</h3>').append('<p>' + err + '</p>');
    },
    dataType: 'text'
});