Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

cordova - PhoneGap: Opening external URL's in Safari

I've just upgraded to PhoneGap 1.6.1 and I can no longer get external URL's to open in Safari.

Prior to this version I had patched AppDelegate.m as follows:

- (BOOL) webView:(UIWebView*)theWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if ([[url scheme] isEqualToString:@"http"]) {
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    } else {
        return [self.viewController webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];
    }
}

I notice that a similar question has been asked before: How can I open an external link in Safari not the app's UIWebView?

But it looks to me like this answer no longer works on version 1.6.1.

I've also tried setting OpenAllWhitelistURLsInWebView in Cordova.plist but neither setting gives me Safari.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...