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!

 1//
 2// Created by Marcus Rohrmoser on 05.12.13.
 3// Copyright (c) 2013 Marcus Rohrmoser mobile Software. All rights reserved.
 4//
 5
 6#import "UIWebView+JavaScriptNSError.h"
 7
 8#define NSERROR_UIWEBVIEW_SCRIPT @"NSERROR_UIWEBVIEW_SCRIPT"
 9#define NSERROR_UIWEBVIEW_SCRIPT_CODE 1
10
11@implementation UIWebView(JavaScriptNSError)
12
13-(NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script error:(NSError * __autoreleasing *)error
14{
15  NSString *errorPrefix = NSERROR_UIWEBVIEW_SCRIPT;
16  NSString *exec = [NSString stringWithFormat:@"try { %@ } catch (e) { '%@' + e; }", script, errorPrefix, nil];
17  NSString *ret = [self stringByEvaluatingJavaScriptFromString:exec];
18
19  if( ![ret hasPrefix:errorPrefix] )
20    return ret;
21
22  if( error ) {
23    NSString *msg = [ret substringFromIndex:errorPrefix.length];
24    NSDictionary *ui = @ {
25      NSLocalizedDescriptionKey: msg,
26      NSFilePathErrorKey:[self.request.URL absoluteString],
27      NSURLErrorKey: self.request.URL,
28      NSLocalizedFailureReasonErrorKey: msg,
29      NSURLErrorFailingURLErrorKey: self.request.URL,
30      NSURLErrorFailingURLStringErrorKey: self.request.URL
31    };
32    *error = [NSError errorWithDomain:NSERROR_UIWEBVIEW_SCRIPT code:NSERROR_UIWEBVIEW_SCRIPT_CODE userInfo:ui];
33  }
34  return nil;
35}
36@end