Theme Preview with Style

(ressuscité depuis https://web.archive.org/web/20140506030559/http://dev.over-blog.com/theme-preview-with-style)

A very big feature of Overblog Kiwi is the new way to design your blog. We make it possible to write some template code like Wordpress, Blogger or Tumblr. To help designers to write their design quickly, we made a cool user interface with a live preview. And we just sublimed it before the release!

Iframe injection

The initial user interface was taking the template code (a Twig variant) and was compiling it with a javascript rendering tool. That was giving us a string with the entire html page. So we were appending an iframe to the main page and inserting this html code as its body's innerHTML.

The goal was to avoid requesting the server after each design change. The user doesn't have to wait for the server to retrieve its data, recompute the web page, and send it back to him. All is working on the client side.

The bad side is that injecting html like that is not 100% like the real rendering on the blog. Especially: javascript can't be ran.

FileSystem API

Then, I discovered the FileSystem HTML5 API. This API allows a website to create and manage files in a sandbox. It can create, delete, alter files and folders which will only be accessible by the same website. It's a way (the only) to write files on the client computer. It's secure thanks to the sandbox: the website can only access to the files in its sandbox, and no other websites can access those.

The idea I had was to write the rendered content in a file, then load the file in the iframe exactly in the same way you are doing it when you create an html file with your text editor and load it in your browser.

And it worked.

How does it work?

It's actually really simple. All we have to do is request a FileSystem instance, create a new file, append some text to it, then get its URL that we will set as the iframe's src attribute.

window.requestFileSystem(  
  window.TEMPORARY,
  1024*1024,
  function(fs) {
    fs.root.getFile(
      'themepreview.html',
      {create: true},
      function(fileEntry) {
        fileEntry.createWriter(function(fileWriter) {
          fileWriter.onwriteend = function() {
            // alert(fileEntry.getURL());
            // => 'filesystem:http://myhost.com/temporary/themepreview.html
            iframe.setAttribute('src', fileEntry.getURL());
          };
        });
        var bb = new BlobBuilder();
        bb.append('Some HTML soup');
        fileWriter.write( bb.getBlob('text/html') );
      }
    );
  }
);

There is only one remaining drawback… Only Chrome supports this API right now. So we have to keep the old method for the older browsers.

Hadrien

Hi, I'm a french Web Lead Developer, Front End Architect from Toulouse, France. I've worked for 7 years for Overblog then 2 years with AngularJS. Now, I'm a great fan of Aurelia.io.

Toulouse, France https://hadrien.eu