問題描述
在我的 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" 的問題,并在 webview 中保持打開標準鏈接.
This solves both the target="_blank" issue to open in safari, AND keeps opening standard links within the webview.
這篇關于打開目標=“_blank";Safari 中 UIWebView 之外的鏈接的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!