Skip to content


iPhone “view source” bookmarklet with syntax highlighting

by frank on December 15th, 2010

When surfing with mobile safari I sometimes miss a show source function to see the source code of websites.

Some solutions are described here. I like the ‘pure bookmarklet’ approach most, as it is quite fast and uses the real source, which is actually loaded by mobile safari. The solutions using a redirect are sending the url to another website, causing the other page to load the source again. So, the page is loaded by another clientand you cannot be sure if this is really the source which is loaded by mobile safari.
Therefore I used the bookmarklet from Dustin Caruso and added syntax highlighting by calling a prettifiy script from google.

This is the source of my bookmarklet:

  var w ='about:blank'),
  doc = w.document;
  doc.write('<!DOCTYPE html><html><head><title>Source of ' + location.href +
    '</title><meta name=\'viewport\' content=\'width=device-width\' />' +
    '<link rel=\'stylesheet\''+
    ' href=\'\''+
    ' type=\'text/css\'/>' +
  var pre = doc.body.appendChild(doc.createElement('pre')); = 'auto'; = 'pre-wrap'; = 'none';
  pre.className = 'prettyprint';
  var lib = doc.createElement('script');
  var call = doc.createElement('script');
  var txt = doc.createTextNode('window.setTimeout(function () {prettyPrint();},600);');

You can try it the usual way: Copy the code to the clipboard, then create a link. Right click on the link and choose ‘Edit Address’ and paste the code as link address. Save the link. Don’t be confused if the code does not appear as expected (this happened to me when I started working with bookmarklets; it is due to the fact that the litte input fields for the link address are not made for lengthy code).

The easiest way to get the link on the iOS device is to create it in desktop safari and syncronize it via iTunes.

The call to prettyPrint() has a timeout. The timeout needed depends on the length of the page. For small pages, a shorter timeout is sufficient (like 200ms), the given timeout of 600ms was enough even for big pages.

The result should look somewhat like this:

iphone show source

Comments are closed.