Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Debug JavaScript in Mobile Safari (iOS) in 7 Easy Steps

DZone's Guide to

Debug JavaScript in Mobile Safari (iOS) in 7 Easy Steps

Here's a tutorial on how to debug JavaScript code being run in Safari on iOS devices using Safari Web Inspector.

· Mobile Zone ·
Free Resource

This article will focus on debugging JavaScript code being run in Safari on iOS devices using the desktop Safari Web Inspector. Being able to debug code being run on an iOS device through the desktop developer tools that we’re familiar with is a huge benefit and can reduce debugging time dramatically.

Gone are the days of using alert calls to debug!

The steps we are going to follow are:

  1. Sample Project Introduction
  2. Analyse a Raygun Error Report
  3. Connecting your Device
  4. Explore the Anatomy of Web Inspector
  5. Add Breakpoints to your Code
  6. Step through your Code
  7. Determine the State of your Application
  8. Fix the Bug!

So, let’s dive in!

Step 1: Sample Project Introduction

To demonstrate how to debug an application with Safari’s Web Inspector, I’m going to use a simple Add Person form. This form allows you to enter a first, middle and last name. On clicking the ‘Save’ button, the form will do a bit of processing, and the data will be sent off to your (imaginary) server.

Mobile Safari Debug Example

The code for this form has three functions:

  • A click handler
  • A capitalize string function
  • A save function
var saveButton = document.getElementById('saveButton');
var firstNameField = document.getElementById('firstName');
var middleNameField = document.getElementById('middleName');
var lastNameField = document.getElementById('lastName');

function onSaveButtonClick(){
    var firstName = firstNameField.value;
    var middleName = middleNameField.value;
    var lastName = lastNameField.value;

    // capitalise the names
    firstName = capitalizeString(firstName);
    middleName = capitalizeString(middleName);
    lastName = capitalizeString(lastName);

    doSave(firstName, middleName, lastName);
}

function capitalizeString(value){
    return value.split('')[0].toUpperCase() + value.slice(1);
}

function doSave(firstName, middleName, lastName){
    alert(firstName + ' ' + middleName + ' ' + lastName + ' has been saved!');
}

saveButton.addEventListener('click', onSaveButtonClick);


Unfortunately, after shipping this to production late on a Friday evening, you start to see error reports coming into your dashboard. There’s a bug, and you need to fix it. Fast.

Step 2. Analyse the Raygun Error Report

Error reports that come into Raygun have plenty of info you can use to find and fix the error, so let’s have a look at what we’re dealing with.









Mobile Safari Raygun Error ReportThe information you will need to debug the error is located in the Stacktrace module.

The Message part of the Stacktrace is a short overview of what is wrong. In this case, the toUpperCase method is being called on an undefined value.

The Stacktrace tells you where the error occurred and the sequence of function calls that led there. As you can see in the screenshot above, the error happened in the capitalizeString function on line 20 of the index.js file.

Knowing which line triggered the error means you can jump straight to the place where the error occurred and start digging into what has caused the problem.

Step 3: Setting Up and Connecting Your Device

Before we can get started with using the Web Inspector to debug our app we must first enable both the iOS and OSX browsers for development.

Enable Web Inspector on iOS

On your iOS device (whether it’s an iPhone, iPad or iPod Touch) navigate to the Settings app and scroll down and select the Safari entry.

Mobile Safari Devs Tools Settings

Inside the Safari settings screen scroll to the very bottom and select the “Advanced” option.

Within the Advanced section, toggle ON the “Web Inspector” option.

Mobile Safari Debug Advanced Settings

Enable Develop Menu on OSX

With your device set up, we need to launch Safari on OSX to enable the Develop menu. Open Safari’s Preferences dialog by clicking the “Safari” menu item and selecting “Preferences…”

Mobile Safari Dev Menu Preferences

Inside the Preferences dialog, go to the Advanced tab and then check the “Show Develop menu in menu bar” option at the bottom.

Mobile Safari Show Develop Menu

You can now close the Preferences dialog.

Connecting Your Device

To allow OSX Safari to communicate with your iOS device we need to connect it to your computer via the standard USB cable.

Open up the Example App

Finally, let’s open the example web app on your iOS device in a new Safari tab. With that done, we’re ready to go!

Step 4: Exploring the Anatomy of Web Inspector

Now the Safari browsers are ready and our device is connected we can open the Web Inspector.

Open the “Develop” menu and you should see an entry near the top showing the name of your device (for example, “Stuart’s iPhone”). Hover on this item so the menu slides open. The new menu will display all the tabs open in Mobile Safari and that the Web Inspector can be connected to. Click the item relating to the example app.

Mobile Safari Web Inspector

The Web Inspector will now open and we’re ready for debugging. The Web Inspector you see now is identical to the one you would see if you had opened it from a page in Desktop Safari, it is just pointing to a tab instance open on your device.

In the Web Inspector window, the Console tab will be active. This tab allows you to execute arbitrary JavaScript code at any time or to view any outputs from console.log calls.

Try entering alert('Hello!'); and hitting Enter—you should see the alert appear straight away.

Mobile Safari Alert Hello

The Console tab is a valuable debugging tool as you can use it as a scratch pad for trying out code and evaluating variables as you diagnose your problem.

To debug the code, you first need to be able to navigate through your source code in the Web Inspector. You do this in the Debugger tab.

Mobile Safari Debuger Tab

The lower half of the left pane inside this tab has a list of all the source files loaded into the page. You can click any of these file names and the contents are displayed in the central pane. You can expand an additional pane containing debugging tools by clicking the button at the top right of the tab.

If you have a lot of files, you can search them by using CMD-P on OSX and then start typing the name of the file.

In the app, you know the problem lies in the index.js file, so select it from the list on the left to view its contents.

Step 5: Add Breakpoints to Your Code

Now you can view your code, we want to be able to step through it a line at a time to see where things go wrong. To do this, we use breakpoints. Breakpoints are markers at specific points in the code which stop execution so you can inspect the state of the code at that point in time, and continue execution line-by-line.

There are a few different ways to add breakpoints which I’ll go over here:

Line Breakpoints

Probably the most common way to add a breakpoint is to find the specific line you want to stop on and add it there. Navigate to the file and line you are interested in and click the line number. A blue marker will be added on that line and execution will stop every time it hits this line of code. In the screenshot below it will stop on Line 7 of index.js.

Mobile Safari Line Breakpoints

You will also notice that a list of the breakpoints you have added is maintained at the top left of the tab. This is useful for navigating to quickly them or temporarily disabling them by clicking the marker beside it.

To remove a breakpoint, right-click the line marker and select “Delete Breakpoint”.

Programmatic Breakpoint

You can also add breakpoints programmatically which can be useful if you don’t want to search through your code in Web Inspector when you have it handy in your IDE. You can also use this approach to conditionally introduce breakpoints, for example at certain iterations of loops, or if the code runs on page load and there’s no time to add the breakpoint manually.

To do this, you add the debugger; statement at the position you want to break the execution. The code below will have the same effect as the Line Breakpoint above.

Error Breakpoint

Web Inspector has a handy feature which will stop execution when it hits an exception in your code, allowing you to examine what’s going on at the time of the error. You can even choose to stop on exceptions that are already handled by a try/catch statement.

To stop when any exception happens, click the arrow icon beside the label “All Exceptions”, you will see it darken when activated. To only stop when an uncaught exception occurs, click the arrow icon beside the “Uncaught Exceptions” label.

Mobile Safari Debug Label

Step 6: Step Through Your Code

Now that we know how to break into our code we now want to step through each line so we can figure out what’s going wrong. First, put a breakpoint on Line 7 - just inside the Add button’s click handler so we can start at the beginning.

In the previous section, we inferred from the Raygun error report that the error came from the capitalizeString method. This method is called three times, so, which instance is the culprit? You can look a little closer at the Stacktrace and see that it was the call that came from Line 13 which caused the error. You know that line 13 relates to the Middle Name value. Therefore, you should focus your effort on reproducing the error by crafting your input correctly.

With this extra knowledge, you can fill in the First and Last Name fields but leave the Middle Name blank to see if this triggers the error.

Mobile Safari Debug Example

Hit the Save button. From here, the Debugger tab will open where you can see the breakpoint activated. You can now start to step through the code. To do this, you use the four buttons in the debugging pane.

Mobile Safari Dev Tools Play Pause

Resumes execution of your code and continues until the next breakpoint Steps over the current line, moving us on to the next line Steps into the next function call that is on that line Steps out of the current function call, back up the callstack one level.

You’re going to use these to step all the way to your capitalizeString function. So from Line 7, use the “Step over” button until we get to Line 13. The active line is shown with a green background.

Mobile Safari Debugger Paused

You can now use the “Step into” button to move into the call to the capitalizeString function.

Mobile Safari Capitalise String

When you’re moving through the code like this, you might want to jump back to a parent function to check what was happening at that point. To do this, use the Call Stack section, which lists all the functions that have been passed through to get to this point in your code—exactly the same as the Callstack shown in the Raygun error report.

Mobile Safari Navigating Call Stack

You can simply click on an item in this list and you will be moved back to that function. Bear in mind that the current position in the execution doesn’t change, so using the Step Over buttons will continue from the top of the call-stack.

Step 7: Determine the State of Your Application

Now you’ve navigated to where your error happened we need to examine the state of the application and figure out what’s causing the error.

There are a bunch of options for figuring out what values variables contain and evaluating expressions before the code moves on. We’ll look at each in turn:

Mouse Hover

The simplest way to determine the value of a variable is to just hover the mouse over it and a tooltip will pop-up with the value. You can even select a group of expressions and hover over the selection to get the output of the expression.

Mobile Safari Output Expression

Watchers

You can add expressions to the Watch Expressions panel which displays the current value of the expression as you move through the code. This is handy to keep track of how more complex expressions change over time.

You add these by clicking the “+” button at the top of the panel, entering the expression to watch and hitting enter.

Mobile Safari Watchers

Scope

The Local Variables section display a list of variables currently within scope and their associated values. This is similar to the Watch Expressions panel but is generated by the Web Inspector automatically. This section is good for identifying local variables and saves you explicitly adding them to the Watch Expressions list.

Mobile Safari Scope

Console

Finally, the Console tab is a great tool for checking expression values and experimenting with code. Just switch back to the Console tab, type some code and hit enter. Web Inspector will execute the code within the context and scope of the current breakpoint.

Step 8: Fix the Bug

Switch over to the Console tab and let’s start to break down the line that caused the error so you can fix it using the Console tab

First, check the output of the value.split(‘’) call so you can get the first character then call the toUpperCase function on it.

Executing the expression in the Console shows it returns an empty array—this is where the error comes from! Since it returns an empty array and we try to call toUpperCase on the first item (which is undefined, since there are no items) that gives you the error.

You can verify this by entering the full expression into the Console:

Mobile Safari Console

So, to fix the problem, you need to check that the string is either empty or undefined. If it is, you need to return an empty string back without doing any processing.

function capitalizeString(value){
    if(!value || value.length === 0){
        return '';
    }

    return value.split('')[0].toUpperCase() + value.slice(1);
}





Summary

That wraps up this quick intro to debugging JavaScript in Mobile Safari with Web Inspector. It is really simple to enable this remote debugging and get the full use of the Safari Web Inspector for pages open on an iOS device. Fortunately, debugging tools for mobile have come a long way and this has made tracking down mobile specific bugs so much easier.

I hope you’re able to put it to use when trying to track down your next Mobile Safari bug. It is really worthwhile taking the time to master these tools to level up your debugging skills!

There are a number of other great features in the Web Inspector that I haven’t touched on here so I encourage you to have a play around and experiment with it.

This article first appeared on the Raygun Blog.

Topics:
debugging ,javascript ,safari ,raygun ,mobile ,tutorial ,ios

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}