WKWebView target=_blank quirks

My previous post deals with the different javascript-related WKWebView quirks . The first issue I mention is

WKWebView does not open any <a> links that have target=”_blank

In summary from the previous post, This issue can be resolved by implementing WKUIDelegate method as below to intercept links that request for a new webView ( new tab/window) and force them to render in the current instance of webView.

During my testing of our company’s app with the above fix, I found that clicking links inside any google plus site result in empty page rendering in WKWebView.

To summarize:

  • Clicking on SOME <a> links with attribute target=”_blank” result in empty page rendering

Upon debugging, I figured out that the WKUIDelegate method is indeed getting called as expected, but the navigationAction.request is empty ( Optional(“”))

After posting a stack over flow question here and trying out remote safari debugging as described here, I still could not figure out why the WKWebView delegate has an empty url passed in as request.

So, I used the fallback option of executing javascript code in the WKNavigationDelegate method of didFinishNavigation that gets called once the webPage is loaded

The javascript code does the following:

  • Get the list of all the links in the web Page
  • Loop through the list of links and do the following
    • If the link has a target attribute set AND the attribute value is “_blank” , we update the attribute value to be “_self”

_self indicates that the link referenced in <a> tag needs to be opened in the current instance of webView instead of new tab or new window ( target = “_blank” indicates that the browser should try and open the link in new window/tab)

Refer here for details on different values of  target attribute.

With this code, the links inside google plus posts open in the same WKWebView instance  ( Eg: tom cruise google plus posts and click on any link)

WKWebView continues to give me these quirks/headaches, though in all fairness this issue exists in UIWebView as well. UIWebView also does not have the fancy delegate method as WKWebView for intercepting calls to create new webViews, so if you are using UIWebView, javascript code is your only option

WKWebView target=_blank quirks

Leave a Reply

Your email address will not be published. Required fields are marked *