iOS Send messages from JavaScript and Handle them on the native side


Example

Messages can be sent from JavaScript using the following code

window.webkit.messageHandlers.{NAME}.postMessage()

Here how to create a script message handler to handle the messages:

class NotificationScriptMessageHandler: NSObject, WKScriptMessageHandler {
    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage!) {
        if message.name == "{NAME}" {
            // to be sure of handling the correct message
            print(message.body)
        }
    }
}

Here how to configure the script message handler in the WKWebView:

let configuration = WKWebViewConfiguration()
let userContentController = WKUserContentController()
let handler = NotificationScriptMessageHandler()
userContentController.addScriptMessageHandler(handler, name: "{NAME}")
configuration.userContentController = userContentController 
let webView = WKWebView(frame: self.view.bounds, configuration: configuration)

NOTE: adding same "{NAME}" handler with addScriptMessageHandler:name: more than once, results in NSInvalidArgumentExceptionexception.