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


Messages can be sent from JavaScript using the following code


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

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

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.