View source on the iPad and iPhone

Update: The bookmarklet has been updated to work with iOS 13+ and without a server backend

My new iPad has become my primary tool for surfing, but alas it completely lacks a view source feature for looking at the source code of all those websites.

To get around this limitation we can use a bookmarklet which is a piece of JavaScript saved as a bookmark. When you click the bookmark, the source code of the current page will be shown in a new window with a few bells and whistles:

  • The code is syntax highlighted (using Prism)
  • Links are clickable, so you can follow scripts etc.
  • Text is fully selectable

Clicking the bookmarklet will display the source of the web page in a new window/tab

The code

The following bookmarklet code copies the DOM and shows it in a new window with syntax highlighting:

javascript:(() => {
  var e = 'https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0',
  t = window.open('about:blank').document;
  t.write(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>Source of ${location.href}</title>
        <link rel=stylesheet href=${e}/themes/prism.min.css>
      </head>
      <body bgcolor=#f5f2f0>
        <script src=${e}/components/prism-core.min.js></script>
        <script src=${e}/plugins/autoloader/prism-autoloader.min.js></script>
        <script src=${e}/plugins/autolinker/prism-autolinker.min.js></script>
      </body>
    </html>`),
  t.close();
  var r = t.body.appendChild(t.createElement('pre')).appendChild(t.createElement('code'));
  r.className = 'language-html',
  r.appendChild(t.createTextNode(document.documentElement.outerHTML))
})();

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"

Edit the bookmark and paste the bookmarklet code

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.

Originally inspired by this bookmarklet from Rob Flaherty.