Home:ALL Converter>Message handler not working in WKWebView in iOS 9

Message handler not working in WKWebView in iOS 9

Ask Time:2019-04-09T00:33:14         Author:Martin Claesson

Json Formatter

I've created an app that uses WKWebView to display an HTML page. I have embedded a button that calls a javascript function to post a message to my code. This works perfectly on iOS 12, but when I debug for iOS 9 it doesn't work at all. The message handler doesn't get called.

I've tried a couple of different ways to make this work for iOS 9 but it seems that nothing is working.

This is my swift code:

let config = WKWebViewConfiguration()
let content = WKUserContentController()

content.add(self, name: "callback")
config.userContentController = content

page = WKWebView(frame: self.WKBaseView.bounds, configuration: config)

This is how i handle the message:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

        dump(message.body)

}

This is what I call from the JS:

try {
      webkit.messageHandlers.callback.postMessage("test");
    } catch(err) {
      console.log('Can not reach app');
    }

Since this works perfectly on iOS 12, is this a bug in iOS 9 or is there some other way of accomplishing this?

Author:Martin Claesson,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55577900/message-handler-not-working-in-wkwebview-in-ios-9
yy