iOS webView open a JavaScript link in Safari

Friday 27 January 2012

After working on updates for our Virtual Swanage iOS app that uses a JavaScript based webview for information, I ran into a problem where by a JavaScript window.location event would only open up a page within an existing view and it was not possible to make a URL jump out of an application and into Safari without resorting to <a> links. I came up with the following solution to get around this problem.

The code below should be placed in your iOS application within the same class as your webview. When a link on a web page is selected the shouldStartLoadWithRequest method is called. The URL request is checked and if the URL contains safari:// or safaris:// instead of http:// or https:// the method overrides the default loading action and passes the URL to safari instead.

By using this method you only need to update any URLs on your website that you want to open in Safari with safari:// instead of http:// or safaris:// instead of https://.

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = [request URL];
    NSString *currentURL = [url absoluteString];
    NSRange textRange = [currentURL rangeOfString:@"safari://"];
    NSRange textRangeSecure = [currentURL rangeOfString:@"safaris://"];
    if((textRange.location != NSNotFound) || (textRangeSecure.location != NSNotFound))
      NSString *newURL;
       if(textRange.location != NSNotFound){
          newURL= [currentURL stringByReplacingOccurrencesOfString:@"safari://" withString:@"http://"];
       if(textRangeSecure.location != NSNotFound){
          newURL= [currentURL stringByReplacingOccurrencesOfString:@"safaris://" withString:@"https://"];
       url = [NSURL URLWithString:newURL];
       [[UIApplication sharedApplication] openURL:url];
       return NO; 
       return YES;