Send messages from JavaScript and Handle them on the native side

suggest change

Messages can be sent from JavaScript using the following code. Replace {NAME} with the handler name, and pass a body postMessage can archive (string, number, date, array, dictionary, or null).

window.webkit.messageHandlers.NAME.postMessage("payload")

Here is how to create a script message handler to handle the messages. This sample is Swift 2.

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 is 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 the same "NAME" handler with addScriptMessageHandler:name: more than once raises NSInvalidArgumentException.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents