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.
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.
But I don't want to open all links the the WebView, just some.
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.
Any idea how to do this?
There is no way to force it to open the url in safari and not open the app. Every app will have list of urls that it can open. So you have to go to that app settings and tell that it should open in browser for the urls and not in the app.
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 ]; } }
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.
Hope this helps
UPDATE :
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];
Just catch all links in your javascript that have target="_blank"
, and pass them to window.open with the '_system' param. This will work on both iOS and Android.
$(document).on('click', 'a[target="_blank"]', function(ev) { var url; ev.preventDefault(); url = $(this).attr('href'); window.open(url, '_system'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With