View source on the iPad and iPhone

As a web developer I'm frequently looking at the source code of various websites. Lately my new iPad has become my primary tool for surfing and reading documentation, but alas it completely lacks a view source feature.

A fine solution is to create a bookmarklet, which is a piece of JavaScript saved as a bookmark. When you want to see the source of a web page, just click the bookmark and the source of the page is displayed. I was inspired by this bookmarklet by Rob Flaherty, but it has a few shortcomings. To improve upon the bookmarklet concept, I created my own version with a few more bells and whistles:

  • The code is syntax highlighted (using GeSHi)
  • Links are clickable, so you can follow scripts etc.
  • Text is fully selectable
Clicking the bookmarklet will display the source of the web page

The code

The following bookmarklet code basically posts the entire DOM to my server, which then takes care of business server-side:

javascript:(function(){
  var w = window.open('about:blank'),
      s = w.document;
  s.write('');
  s.close();
  var f = s.body.appendChild(s.createElement('form'));
      f.setAttribute('method','post');
      f.setAttribute('action','http://ole.michelsen.dk/viewsource/?uri='+location.href);
  var i = f.appendChild(s.createElement('input'));
      i.setAttribute('type','hidden');
      i.setAttribute('name','DOM');
      i.setAttribute('value',encodeURIComponent(document.documentElement.innerHTML));
  f.submit();
})();

How to install it

To add it on your computer and sync it to your iPad, just drag this link to your bookmarks:

View Source (click to try it out)

To add it directly from your iPad (or iPhone), you need to create the bookmark manually:

  1. Add this page as a bookmark
  2. Then click here to see the bookmarklet code and Select All → Copy
  3. Now edit that same bookmark, paste the code you just copied into the URL and name it something like "View Source"

Voilá!

Note that the source shown is the generated DOM, and not the original HTML. These might differ depending on the amount of JavaScript used on the page.

Update April 5, 2012

By popular demand, I have published the server-side PHP code to GitHub, so you can modify or host your own version of the bookmarklet. Remember that GeSHi is required.