IOS Objective C UI WebView Target
- January 22, 2016
- Posted by: Aelius Venture
- Category: Information Technology
No Comments
Now is the iOS add of HTML5, We believe that many people are using H5 to do mobile projects. Apple’s approval today is very loose, and been different from the previous rejection of the pure UIWebview project.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
if ([request.URL.absoluteString hasPrefix:@"newtab:"])
{
// JS-hacked URl is a target=_blank url - manually open the browser.
NSURL *url = [NSURL URLWithString:[request.URL.absoluteString substringFromIndex:7]];
[[UIApplication sharedApplication] openURL:url];
return true;
}
return true;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// JS Injection hack to solve the target="_blank" issue and open a real browser in such case.
NSString *JSInjection = @"javascript: var allLinks = document.getElementsByTagName('a');
if (allLinks) {var i;for (i=0; i<allLinks.length; i++) {var link = allLinks[i];
var target = link.getAttribute('target'); if (target && target == '_blank')
{link.setAttribute('target','_self');link.href = 'newtab:'+link.href;}}}";
[webView stringByEvaluatingJavaScriptFromString:JSInjection];
}