Tuesday, December 16, 2014

oEmbed CodePen or How to embed CodePen without oEmbed plugins using serverside calls...

Recently I've been working on my new project Get JSON - I've had some brilliant responses from users on both Twitter and CodePen alike. One of my pens even got picked for the front page - something which I did not expect but am indeed truly grateful for.

Get JSON allows you to create ad-hoc data structures in JSON format and then pull them into either client or server side code for use within your application. It's great for semi-static lists, configuration info or indeed any data that can be modelled hierarchically.

I thought it might be a good idea to include the Pen whilst viewing the data so that other users have a "serving suggestion" showing how the data could be accessed and modelled. In order for this function to work it required making a call using oEmbed in order to retrieve the iframe info needed to get the Pen onto the page.

Upon investigation however I had significant difficulty getting this to work. Having tried several plugins to no avail I decided to simply write my own script to make the call to get the JSON containing the iframe code myself. Below is the code currently used in order to make the call to get the JSON containing the iframe code. Underneath the C# server side code is the JavaScript I used in order to get the Pen displayed on the page.

C# MVC 5 Controller

var request =
      WebRequest.CreateHttp(string.Format("http://codepen.io/api/oembed?&url={0}",
        codePenUrl));
request.Accept = "application/json";
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
request.Headers.Add(HttpRequestHeader.AcceptLanguage,
                 "en-GB,en;q=0.8,en-US;q=0.6,cy;q=0.4,ceb;q=0.2");
var json = string.Empty;
using (var response = await request.GetResponseAsync())
{
  using (var reader = new StreamReader(response.GetResponseStream()))
  {
    json = reader.ReadToEnd();
  }
}
ViewBag.CodePenDemoFrame = json;
return View();

JavaScript

var codePenJson = @Html.Raw(ViewBag.CodePenDemoFrame);
$('#codePenDemo').append(codePenJson.html);

No comments: