Send messages from JavaScript and Handle them on the native side
suggest changeMessages 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 withaddScriptMessageHandler:name:more than once raisesNSInvalidArgumentException.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents