Thursday, February 28, 2013

iOS Phonegap ( Cordova ) Open Link in Safari


Have you ever encountered the situation in your corodova project where you have set OpenAllWhitelistURLsInWebView to YES in your Cordova.plist file and you have to open one single URL in external Safari application.? If yes than read this blog.


For cordova we have to whitelist some external urls if we have any. By default it will open in external Safari browser to prevent that we have to set following in Cordova.plist file.

This will open all the external urls in same web view. So to add exception URL which should open in external Safari browser make following changes to AppDelegate.m file. 

- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = [request URL];
    NSString* urlString =  [url absoluteString];
    
    if ([urlString rangeOfString:@"www.myexternalurl.com"].location == NSNotFound) {

    }
    else {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
}


and in your JavaScript simply write following line.

window.location.href = "www.myexternalurl.com";

Once web view start loading the url it will invoke shouldStartLoadWithRequest event. Here we are checking the url string and if we find it to be external URL, it will be opened in external Safari browser. Webview will not load this URL since we return NO.

1 comment:

  1. Thanks for sharing your knowledge like this.

    I would like to invite you to try our latest iteration of "AppGyver steroids" for PhoneGap. I believe you will be able to build apps much faster for your customers than ever before.

    www.AppGyver.com/steroids

    Please give it a try and let me know what you think, and let me know if you have any questions; I'd be happy to introduce to to the support team.

    These recent write-ups give a little more context:
    http://techcrunch.com/2013/03/01/pitching-app-ideas-appgyver-delivers-mobile-app-prototypes-in-minutes-no-technical-know-how-needed/

    http://venturebeat.com/2013/06/03/pitching-an-app-appgyver-says-it-can-deliver-gorgeous-prototypes-more-exclusive/

    http://www.infoworld.com/d/application-development/appgyver-aims-make-phonegap-developers-more-effective-using-steroids-220102

    Cheers,
    Michael
    www.AppGyver.com

    Follow me: https://twitter.com/AnAppGyverGuy

    "We will not be remembered for building cool tools that build crappy apps"

    ReplyDelete