Safari中UIWebView外部的链接

Safari中UIWebView外部的链接

本文介绍了打开目标=" _blank" Safari中UIWebView外部的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的iOS应用程序中,我有一个UIWebView。

Inside my iOS Application I have an UIWebView.

现在我希望所有具有属性target =_ blank的链接不能在我的WebView中打开,而是在Safari外部打开。

Now I want all links that have the attribute target="_blank" not to open inside my WebView but externally in Safari.

我该怎么做?

推荐答案

我的回答,哪个这是我在Android WebView的堆栈溢出中找到的答案。但实际上,两个webview都有相同的问题和相同的(脏)修复:

My answer, which is a from an answer I found on stack overflow for the Android WebView. But actually, both webview have the same problem and same (dirty) fix:

- (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];
}

这解决了在safari中打开的target =_ blank问题,AND继续在webview中打开标准链接。

This solves both the target="_blank" issue to open in safari, AND keeps opening standard links within the webview.

这篇关于打开目标=&quot; _blank&quot; Safari中UIWebView外部的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:56