Skip to content
Tags

,

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:

javascript:(function(){
  var w = window.open('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=\'http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css\''+
    ' type=\'text/css\'/>' +
    '</head><body></body></html>');
  doc.close();
  var pre = doc.body.appendChild(doc.createElement('pre'));
  pre.style.overflow = 'auto';
  pre.style.whiteSpace = 'pre-wrap';
  pre.style.border = 'none';
  pre.className = 'prettyprint';
  pre.appendChild(doc.createTextNode(document.documentElement.innerHTML));
  var lib = doc.createElement('script');
  lib.setAttribute('type','text/javascript');
  lib.setAttribute('src','http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js');
  doc.getElementsByTagName('head')[0].appendChild(lib);
  var call = doc.createElement('script');
  call.setAttribute('type','text/javascript');
  var txt = doc.createTextNode('window.setTimeout(function () {prettyPrint();},600);');
  call.appendChild(txt);
  doc.body.appendChild(call);
}());

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.