29

It appears that a lot of links on websites use window.open in their onclick handlers but WKWebView seems to completely ignore window.open.

Is there a workaround for this?

I tried setting javaScriptCanOpenWindowsAutomatically preference to true but that didn't seem to help

Bret
  • 883
  • 1
  • 9
  • 18

1 Answers1

52

When a web application calls window.open() in JavaScript, the WKWebView will call the - webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures: method on its UIDelegate.

In that delegate method you should create a new WKWebView with the WKWebViewConfiguration that is given to you. If you present this new WKWebView on screen, it will load with the correct content.

This is documented in the WKUIDelegate documentation, although it is not very explicit that this is called as a result of window.open().

Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
  • 1
    Could you add information on how to do this with JavaScript? I'm using Cordova! : D – mesqueeb Jan 12 '19 at 02:31
  • It is obvious but you will need to delegate your `webView.uiDelegate` in order to implement this `createWebViewWith configuration`. You will need this if you migrated from `UIWebView` to `WKWebView` as the `window.open` won't work. – vberihuete Dec 02 '19 at 14:31
  • 1
    Hello @Stefan, what possibly could be the issue for the method `createWebViewWithConfiguration` not being trigger? Despite delegate has been set to my webview? Appreciate if you could drop your 2 cents. Details question posted here.. https://stackoverflow.com/questions/60851538/wkwebview-does-not-trigger-method-createwebviewwithconfiguration – Tommy Leong Mar 25 '20 at 15:08
  • For anyone that missed it, you need to set `web.configuration.preferences.javaScriptCanOpenWindowsAutomatically = true` (defaults to false in iOS) – bendytree Apr 11 '23 at 23:54