I've spent the last few days getting the EatDifferent PhoneGap app working on an iPhone (an app which previously worked on Android). The hardest part has been learning to debug in the iOS browser, so I thought I'd post on my findings:
- To view the output of
console.log
, you must open the XCode console. The iOS browser "Debug console" that most iOS debugging articles mention is only displayed in the standalone Safari browser, not in the WebView (where PhoneGap HTML lives). - There seem to be times when
console.log
does not log the output (perhaps during loading?) - in that case,alert()
always seems to work. - If you log a JS object using
console.log
, it will just print"Object"
by default. You must JSON stringify it to be useful. - You can also use debug.phonegap.com (hosted weinre) to view the DOM and JS console logs as well.
- The WebView browser silently fails on JS errors - it stops running the JS code and does not report the error. To see the error, you must wrap the offending code in a try/catch block.
Given all of those learnings, here is my log()
wrapper function that I use across my
webapp:
function log(something) { if (window.console){ if (something instanceof Date) { something = something.toDateString(); } if (isIOS() || isAndroid()) { if (typeof something == 'object') { something = JSON.stringify(something); } console.log(something); } else { console.log(something); } } }
And I wrap various code blocks in try/catch, like the callback function for AJAX requests:
try { onSuccess(processJSON(responseJSON)); } catch(e) { log(e); }
I posted my observations in the PhoneGap group and the developers there made several recommendations: 1) use Ripple, a Chrome extension for mobile emulation 2) monkey-patch JS functions to always try-catch, as done in this library. I've taken a break from iOS debugging for a few days, but I'll probably revisit debugging soon and try out their ideas.