Catch JavaScript exceptions in UIWebViews

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

Flattr this!

Post a Comment

Your email is never published nor shared. Required fields are marked *