How to debug JavaScript (or CSS) on iOS

Sometimes you run into an issue where a web page won’t display correctly on iOS. Since mobile devices don’t have robust debugging tools, you can’t easily troubleshoot issues on the devices. The solution is to use Safari’s Web Inspector and today I’m going to walk you through how to set this up and debug an actual (contrived) JavaScript issue with Safari on Mac OS X.

Please note, this technique will only work with iOS 6 or above. There’s another technique for iOS 5 that I’ll cover in a future blog post.

1: Enable Developer Tools in Safari

First, you need to make sure that you have Safari’s Develop menu visible. If not, open the Safari Preferences, select the Advanced tab, and check the “Show Develop menu in menu bar” checkbox.

Enable developer tools in the Advanced tab of Safari's preferences.
Enable developer tools in the Advanced tab of Safari’s preferences.

2: Enable Web Inspector in iOS

Next, you need to enable the Web Inspector in iOS. This will let you debug your iPad or iPhone (or iPod Touch) over USB. Select Safari in the Settings app and tap the Advanced option. Then turn on the Web Inspector.

Tap the Advanced option in Safari Settings.
Tap the Advanced option in Safari Settings.
Turn on Web Inspector
Turn on Web Inspector

 3: Connect and Debug

Now we’re all setup, it’s time to debug. Connect your iPad to your Mac with a USB cable and open Safari. In the Develop Menu, you’ll see that your iPad now appears.

iPad with browser tabs in Safari Develop menu.
iPad with browser tabs in Safari Develop menu.

After you select the browser tab you want to debug, Safari will open a Web Inspector window for your iPad. Every time you reload the tab on your iPad this Web Inspector will reload. You can even set breakpoints and step through the JavaScript that is executing on your iPad.

You should always look at the console as a first step to debugging JavaScript problems. In Safari’s newest Web Inspector, that’s the speech bubble icon highlighted below.

safari-debugger-for-ipad@2x
View JavaScript console for iPad.

If this were a real JavaScript error, you’d have a line number and some indication of what went wrong and how to fix it. In this case, I’m simply throwing an exception.

 Conclusion

And there you have it. Step-by-step instructions on how to get setup to debug JavaScript problems on iOS. Once you’ve got this setup in place you can debug any kind of display or script error easily.

Next week I’ll show you how to do the same thing for Android.