ruipacheco
ruipacheco

Reputation: 16472

Debugging JS in UIWebView

I have a piece of JS that has been tested on a static HTML page and works fine. I need to call this JS from an HTML file stored in the bundle of my iOS app. The JS itself does a little song and dance on the DOM and displays a div on top top of the rendered page.

When I call this file from a UIWebView I cannot see the JS in action, the DIV is not displayed over the normal HTML.

If I open the remote inspector, copy/paste the HTML into a file and open it from disk, everything works fine. But if I just open the UIWebView, nothing works.

How can I debug this?

Upvotes: 0

Views: 238

Answers (3)

jmf1205
jmf1205

Reputation: 447

For those who come to this question later in its life, this answer provides a nifty console.log() function for the UIWebView.

Upvotes: 0

David Kristensen
David Kristensen

Reputation: 31

You can also get nice text output by running JavaScript in your web view.

Let's say I've got some JS in my UIWebView content,

var myCatsName = "Bob";
var myCatsType = "Silver Tabby";

and i want a description of my cat from my iOS app, assuming you have a UIWebView called webView, just do

NSString* catDescription = [webView stringByEvaluatingJavaScriptFromString:@"myCatsName + ' (' +myCatsType + ')';"];

This means you can also poke at your variables—create a JS array called debugMessages, add to it whatever you want to know, then read it out as a string by joining it with \n as the array element separator.

Instead of using alert(), you simply add a new element to debugMessages. Your iOS app can poll the value of that variable periodically.

It's not an approach that's useful for debugging other people's code, but it is quite useful if you are the one developing the JS :-)

Upvotes: 1

ruipacheco
ruipacheco

Reputation: 16472

For those who are desperate, apparently the only way to debug JS in a UIWebView is with caveman methods. Basically alert() everything that looks suspicious.

Upvotes: 0

Related Questions