如何在 Safari 中打开外部链接而不是应用程序的 UIWebView?
我有一个 Phonegap (cordova) 应用程序,我想在 phonegap WebView 中加载一些外部网页,我还有其他外部网页,我想在用户激活它们时在 safari 中加载它们.
I have a Phonegap (cordova) application where I want to load some external webpages within the phonegap WebView and I have other external webpages that I want to load in safari when the user activates them.
通常大多数人都会遇到想要在 WebView 中打开外部链接的问题.将 OpenAllWhitelistURLsInWebView 设置为 YES(在 Cordova.plist/Phongap.plist 中)可以解决这个问题.
Typically most people have the problem where they want to open an external link in the WebView. Setting OpenAllWhitelistURLsInWebView to YES (in Cordova.plist/Phongap.plist) solves that problem.
但我不想打开WebView的所有链接,只打开一些.
But I don't want to open all links the the WebView, just some.
我希望我可以调用 window.open('http://someexternalsite')
在 Safari 中打开和 window.parent.location.href = 'http://mysite'
在 WebView 中打开它.
I was hoping I could just call window.open('http://someexternalsite')
to open in Safari and window.parent.location.href = 'http://mysite'
to open it in the WebView.
知道怎么做吗?
如果你想在 safari 中打开的链接都包含一个公共字符串,你可以使用下一段代码.
If the links you want to open in safari all contain a common string, you can use the next piece of code.
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url = [request URL];
// Intercept the external http requests and forward to Safari.app
// Otherwise forward to the PhoneGap WebView
if ([[url scheme] isEqualToString:@"SCHEME"]) {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
else {
return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
}
}
放置在 AppDelegate.m
中的这段代码将在 Safari 中打开所有使用指定 SCHEME 的 URL.
This code placed in the AppDelegate.m
will open all URL that use the specified SCHEME in Safari.
恐怕这就是我能想到的全部.
I'm afraid that is all I could come up with.
希望能帮到你
更新:
代码应该放在 MainViewControler 中,至少对于cordova 2.2.0.
The code should be placed in the MainViewControler, at least for cordova 2.2.0.
该方法最初被注释.我不得不用它来重定向谷歌地图链接:
The method is initially commented. I had to use it to redirect Google maps links :
NSRange isGoogleMaps = [[url absoluteString] rangeOfString:@"maps.google.com" options:NSCaseInsensitiveSearch];
NSRange isGoogleTerms = [[url absoluteString] rangeOfString:@"terms_maps.html" options:NSCaseInsensitiveSearch];
if(isGoogleMaps.location != NSNotFound || isGoogleTerms.location != NSNotFound ) {
[[UIApplication sharedApplication] openURL:url];
return NO;
}
else
return [super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType];