PhoneGap: Opening external URL's in Safari

The best way to open links in a new URL is actually with window.open. Just set the target as "_system":

window.open("http://stackoverflow.com", "_system");

Before I found this in the docs, I actually wrote a plugin to do the same. I'm going to leave this answer here, because this would give you much more granular control over handling of links.

With PhoneGap 2.3+, I was unable to get URLs to open in Mobile Safari in any way. Using _blank didn't work, and I tried window.open(url, '_blank'), but this now opens the URL using the InAppBrowser plugin (which pretty much sucks). I thought it was interesting that that one used a plugin though, so I decided to write a plugin to open URLs using the standard method of opening URLs in iOS apps. You can see/grab the code on this gist here: https://gist.github.com/typeoneerror/5097118.

In my example, I wired up links that have a class called "_blank" with jQuery and opened those URLs with the plugin call:

// execute the plugin called OpenUrl, signature:
// exec(successCallback, errorCallback, pluginName, pluginMethod, params)
cordova.exec(success, error, "OpenUrl", "openUrl", [url]);

I have used this in the MainViewController.m

- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    NSString *str = url.absoluteString;
    NSRange range = [str rangeOfString:@"http://"];
    //HACK to make url open in safari
    if (range.location != NSNotFound) {
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    }
    else {
        return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
    }
}

In earlier version of cordova you can load a url in browser by adding target="_blank" to your links. But now you can use inApp browser feature.

var ref = window.open(encodeURI('your url'), '_system', 'location=no');

This opens the url in browser. Tested in Android and iPhone with cordova2.7.0

Tags:

Cordova