fettig.net

View Source for Safari on iPhone

Posted by Abe on Monday, July 2, 2007 @ 8:40 pm

A lot of web development knowledge has been gleaned by viewing source. Unfortunately the iPhone’s version of Safari doesn’t have a View Source command. So if you visit a site on the iPhone, and find that they’re serving you up a different, iPhone-optimized version of the site, there’s no easy way to look at the source and see what they’re doing.

To work around this problem, I made myself a little View Source bookmarklet that works on the iPhone. Here it is:

View Source

To use, add the above bookmarklet to your Safari or IE bookmarks, and sync your iPhone. Then visit a web page on your iPhone, pull up your bookmarks and select “View Source”. A new page will open containing the source of the page you were viewing.

Unlike the traditional View Source command, this bookmarklet shows the generated source, not the original source. if the DOM has been modified by script you’ll see the modified version and not the original. Also, you’ll probably have to do lots of zooming and panning, since the lines of source code will be wide. If anybody wants to make a version that has nicer formatting, feel free to expand this code.

Here’s the original un-escaped javascript:

var sourceWindow = window.open('about:blank');
var newDoc = sourceWindow.document;
newDoc.open();
newDoc.write('<html><head>' +
    '<title>Source of ' + document.location.href + '</title>' +
    '</head><body></body></html>');
newDoc.close();
var pre = newDoc.body.appendChild(newDoc.createElement("pre"));
pre.appendChild(newDoc.createTextNode(
    document.documentElement.innerHTML));