1

On Android, I am using the addJavascriptInterface method to expose a custom API to webpages I load in a WebView.

Is there a similar alternative for the iOS WKWebView?

I came across evaluateJavaScript which allows me to run JavaScript to add my API to the global scope, but I can't figure out a way of adding code that communicates with my app.

David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • 1
    From what I understand you are trying to make javascript communicate with a Webview. I tried to do the same things as you and it worked on Android but not on IOS. There is a way to make them communicate but it's trough only one function. There is a big article that explains it pretty well https://medium.com/@JillevdWeerd/creating-links-between-wkwebview-and-native-code-8e998889b503 – Gilbert Gabriel Jan 16 '20 at 13:42
  • 1
    @GilbertGabriel Thanks that looks like what I need – David Callanan Jan 16 '20 at 13:47
  • No problem! I wrote an answer so if the article fills the needs then feel free to accept it otherwise tell me! – Gilbert Gabriel Jan 16 '20 at 13:50

2 Answers2

4

It is possible. You probably are looking for WKScriptMessageHandler. Create a custom configuration for the web view. For example in your view controller's viewDidLoad.

let configuration = WKWebViewConfiguration()

Register a script message handler with the configuration. For example a view controller, which creates the WKWebView on viewDidLoad. The view controller then needs to conform to WKScriptMessageHandler.

configuration.userContentController.add(self, name: "helloworld")

Programmatically create the web view with the custom configuration.

webView = WKWebView(frame: view.frame, configuration: configuration)

Call the WebKit message handler from JavaScript. Message handlers are available as properties in the global window.webkit.messageHandlers object. properties use the name used when calling WKUserContentController.add(_:name:) above.

window.webkit.messageHandlers.helloworld.postMessage("Hi!");

Handle the call from the JavaScript context.

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print(message.body as! String)
}

Disclaimer: I copied and reduced this code snippets from my own answer to a higher level question of which the solution includes these steps.

p13n
  • 859
  • 8
  • 31
1

It is possible to communicate from a WKWebview to the code but only with one function and it is pretty hard to do but if you manage everything well you can come up with good results. I will let this article explain it because it is a pretty complex process and they will do it better then me.

Creating links between WKWebView and native code

Gilbert Gabriel
  • 422
  • 2
  • 8
  • 23