Why Is Wkwebview Not Opening Links With Target="_Blank"

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

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 webView.evaluateJavaScript(jsCode, completionHandler: nil)
}

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.

  1. class ViewController extends WKUIDelegate
  2. self.webView.uiDelegate = self
  3. Use UIApplication.shared.open instead of webView.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
}

}

A link with swift webview application target _blank is not working

I've created a UIViewRepresentable class for the WKWebView from UIKit. The UIViewRepresentable class can be used to create and manage views(UIView) from UIKit in SwiftUI. There are two views in the project,

  1. ContentView lists the urls from string array. Selecting an url navigates to the Detail view.
  2. The Detail view shows the web page for the selected url using WKWebView.

Hope this helps. Here's the code.

import SwiftUI
import UIKit
import WebKit

struct ContentView: View {
var urls: [String] = ["https://www.stackoverflow.com", "https://www.yahoo.com"]
@State private var hideStatusBar = false

var body: some View {
NavigationView {
List {
ForEach(urls, id: \.self) { url in
VStack {
NavigationLink(destination: DetailView(url: url)) {
Text(url)
}
}
}
}
.navigationBarTitle("Main")
}
}
}

struct DetailView: View {
var url: String = ""

var body: some View {
VStack {
Webview(url: url)
Spacer()
}
.navigationBarHidden(true)
}
}

struct Webview: UIViewRepresentable {
var url: String
typealias UIViewType = WKWebView

func makeUIView(context: UIViewRepresentableContext) -> WKWebView {
let wkWebView = WKWebView()
guard let url = URL(string: self.url) else {
return wkWebView
}

let request = URLRequest(url: url)
wkWebView.load(request)
return wkWebView
}

func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext) {
}
}

WKWebView not opening SOME target=_blank links

I was hoping that I could solve it using the WKWebView delegate methods, but I could not figure it out.

So I went to the UIWebView era's solution of running a javascript function upon completion of web Page loading

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
let jsCode = "var allLinks = document.getElementsByTagName('a');if (allLinks) { var i;for (i=0; i webView.evaluateJavaScript(jsCode, completionHandler: nil)
}

This fixed the issue where tapping on the links in any google plus Posts page was resulting in an empty page being loaded


UPDATE on Nov 3rd 2015: The phenomenon explained in the question, no longer happens for me in Swift 2.0 code. So , you should be able to use the solution presented here for all your purposes

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
}

href target _blank not working properly - not opening link in new tab , javascript handling the event diferently

Problem

Your script (scripts.js) on line 13 toggle animsition's feature for links: linkElement: "a.project-box". This will add an handler to every a element with a project-box class. The handler is the following code (I've commented for your understanding):

function(event) {
event.preventDefault(); // prevent the default behavior for links (prevent the behavior you want)
var $self = $(this);
var url = $self.attr('href'); // get the url of the link
if (event.which === 2 || event.metaKey || event.shiftKey || navigator.platform.toUpperCase().indexOf('WIN') !== -1 && event.ctrlKey) {
// open the link in a new tab ONLY IF I clicked on it with the middle mouse button or with Ctrl/Cmd pressed
window.open(url, '_blank');
} else {
// Else do the animation and open the link in the same tab
__.out.call(_this, $self, url);
}
}

Fix

To fix your problem, you can either

  • Change the way you setup Animsition, be aware that it can modify other links/behaviors in your site
  • Change the class of your link so it is not matched as the linkElement of your Animsition's setup. For example: remove the class of the a element (it will affect the styling) and you will see that the link opens in a new tab.

Appendix

You can find the handler's code in the devtools -> your link element -> handlers -> click.
devtools screenshot



Related Topics



Leave a reply



Submit