Catch JavaScript exceptions in UIWebViews

Thu, 05. Dec 2013

Categories: en development Tags: Catch Cocoa Exception iOS JavaScript NSError Objective C stringByEvaluatingJavaScriptFromString Throw UIWebView

A small but useful category method on UIWebView: Turn uncaught JavaScript Exception into a NSError!


//
// Created by Marcus Rohrmoser on 05.12.13.
// Copyright (c) 2013 Marcus Rohrmoser mobile Software. All rights reserved.
//

#import "UIWebView+JavaScriptNSError.h"

#define NSERROR_UIWEBVIEW_SCRIPT @"NSERROR_UIWEBVIEW_SCRIPT"
#define NSERROR_UIWEBVIEW_SCRIPT_CODE 1

@implementation UIWebView(JavaScriptNSError)

-(NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script error:(NSError * __autoreleasing *)error
{
  NSString *errorPrefix = NSERROR_UIWEBVIEW_SCRIPT;
  NSString *exec = [NSString stringWithFormat:@"try { %@ } catch (e) { '%@' + e; }", script, errorPrefix, nil];
  NSString *ret = [self stringByEvaluatingJavaScriptFromString:exec];

  if( ![ret hasPrefix:errorPrefix] )
    return ret;

  if( error ) {
    NSString *msg = [ret substringFromIndex:errorPrefix.length];
    NSDictionary *ui = @ {
      NSLocalizedDescriptionKey: msg,
      NSFilePathErrorKey:[self.request.URL absoluteString],
      NSURLErrorKey: self.request.URL,
      NSLocalizedFailureReasonErrorKey: msg,
      NSURLErrorFailingURLErrorKey: self.request.URL,
      NSURLErrorFailingURLStringErrorKey: self.request.URL
    };
    *error = [NSError errorWithDomain:NSERROR_UIWEBVIEW_SCRIPT code:NSERROR_UIWEBVIEW_SCRIPT_CODE userInfo:ui];
  }
  return nil;
}
@end