Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebKit userContentController:didReceiveScriptMessage: not getting called for iOS 13

I am using WKWebView for showing web content into my app but I am not able to get a message sent from JS webkit on iOS 13 devices.
On previous iOS versions, it's working as expected.

Setup:

func setupWebView() {
    let config: WKWebViewConfiguration = WKWebViewConfiguration()
    config.userContentController.add(self, name: "mobileApp")
    webView = WKWebView(frame: self.view.frame, configuration: config)
    webView?.navigationDelegate = self
    webView?.uiDelegate = self
    webView?.scrollView.bounces = false
    webView?.backgroundColor = UIColor.clear

    self.view.addSubview(webView!)
    self.webView?.load(URLRequest(url: URL(string: self.stringURL!)!))
}

WKScriptMessageHandler Delegate:

func userContentController(_ userContentController: WKUserContentController, 
                                didReceive message: WKScriptMessage) {
    let data = NSMutableDictionary(dictionary: message.body as! Dictionary)
    //Method is not getting called
}

From JavaScript I am calling it like this :

webkit.messageHandlers.mobileApp.postMessage({ 'backToApp': '1' });

Please let me know if anyone has come across this issue and some possible solution to it.

like image 798
Jarvis The Avenger Avatar asked Feb 27 '26 02:02

Jarvis The Avenger


1 Answers

After lots of searching, I found the solution that in iOS 13 user agent property is changed which we were used in WEB to check if it is mobile or not. isMobile check was failing because of that our message handler was not getting called.

A lot of breaking changes have been done in iOS 13 that currently we need to take care.

like image 113
Jarvis The Avenger Avatar answered Feb 28 '26 16:02

Jarvis The Avenger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!