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.