Send messages from JavaScript and Handle them on the native side

suggest change

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.

Feedback about page:

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


WKWebView:
* Send messages from JavaScript and Handle them on the native side

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
40 iBeacon
49 NSTimer
71 WKWebView
79 NSURL
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable