WKWebView target=_blank link open new tab in safari ios11, swift 4
I have pasted some sample code of a WKWebView project (load local html from folder) that requires links that have target=_blank
to open in a new browser window.
I have highlighted the 3 things you must have to get links to open correctly.
class ViewController extends WKUIDelegate
self.webView.uiDelegate = self
- Use
UIApplication.shared.open
instead ofwebView.load
Let me know it it works and if anyone can suggest improvements to the sample code below, that would help me too :)
Full sample code for Xcode 9.2, Swift 4 below.
Good Luck
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.webView.uiDelegate = self
let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "www")
let htmlUrl = URL(fileURLWithPath: htmlPath!)
let htmlDir = Bundle.main.url(forResource: "www", withExtension: nil)
webView.loadFileURL(htmlUrl, allowingReadAccessTo: htmlDir!)
}
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil {
//webView.load(navigationAction.request)
UIApplication.shared.open(navigationAction.request.url!, options: [:])
}
return nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var prefersStatusBarHidden: Bool {
return true
}
}
Open a WKWebview target=_blank link in Safari
Code updated for iOS 10 Swift 3:
override func loadView() {
super.loadView()
self.webView.navigationDelegate = self
self.webView.uiDelegate = self //must have this
}
func webView(_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil, let url = navigationAction.request.url {
if url.description.lowercased().range(of: "http://") != nil ||
url.description.lowercased().range(of: "https://") != nil ||
url.description.lowercased().range(of: "mailto:") != nil {
UIApplication.shared.openURL(url)
}
}
return nil
}
iOS14, WKWebView cannot open links with _blank target
At the moment of writing this, WKWebView has some "unknown" bug with parsing the _blank target attributes of href tag.
It seems that Safari works properly when the target is _self.
The idea is to replace all _blank values with _self.
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
let jsCode = "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');} } }"
webView.evaluateJavaScript(jsCode, completionHandler: nil)
}
Why is WKWebView not opening links with target=_blank?
My solution is to cancel the navigation and load the request with loadRequest: again. This will be come the similar behavior like UIWebView which always open new window in the current frame.
Implement the WKUIDelegate
delegate and set it to _webview.uiDelegate
. Then implement:
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
WKWebView Open _Bank Target Links in Safari
This is what eventually worked for me. Seems to open any url (including javascript type popovers used in YouTube) in Safari instead of opening them in WKWebView (or not opening them at all).
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
NSLog(@"createWebViewWithConfiguration %@ %@", navigationAction, windowFeatures);
if (!navigationAction.targetFrame.isMainFrame) {
[[NSWorkspace sharedWorkspace] openURL:[navigationAction.request URL]];
}
return nil;
}
Related Topics
Could Not Cast Value of Type 'Uiview' (0X112484Eb0) to 'Skview' (0X111646718)
How to Detect Tap on Clear Part of Uitableview
iPhone Mkmapview - Mkpolygon Issues
Ios8 Extension and Container App How to Share Data
Cashapelayer Animating Path Glitches/Flickers (From Ellipse to Rect and Back)
Makekeywindow VS Makekeyandvisible
How to Add Firebase to Today Extension iOS
In-App Purchase Sandbox Environment Loop
How to Evaluate the String Equation in iOS
Select Items Programmatically in Uicollectionview
Ios: Production Push Notifications, Invalid Token from Apns Server
Gcd - Main VS Background Thread for Updating a Uiimageview
Uilabel, Uifont and Utf-8 Triangle
How to Access User Defined Runtime Attribute from the 'Sender' Object
Swift - How to Open Specific View Controller When Push Notification Received