Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return result from called function in iOS to calling function in WkWebView in JavaScript

We called a function in iOS from javascript i.e

var data = webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");

I want to assign returned value in data variable from called method in iOS.

iOS Code :

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(message.name == "callbackHandler") {
            print("JavaScript is sending a message \(message.body)")
            how to send data back??
        }
    }

can someone please tell me how to do it??

I know I can use evaluateJavascript to call back another method but due to some restriction I have to return result from same method.

like image 435
yuvraj Sorav Avatar asked Jun 25 '26 15:06

yuvraj Sorav


2 Answers

Here is one approach:

Javascript:

function callNativeCode() {
    webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
}

// this function will be later called by native code
function callNativeCodeReturn(returnedValue) {
    // do your stuff with returned value here
}

Swift:

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if(message.name == "callbackHandler") {
        print("JavaScript is sending a message \(message.body)")
        webView.evaluateJavaScript("callNativeCodeReturn(0)")
    }
}

Of course this is not very elegant and not synchronous...

There is another approach with promises, you can find out more about it here: http://igomobile.de/2017/03/06/wkwebview-return-a-value-from-native-code-to-javascript/

like image 119
ndreisg Avatar answered Jun 27 '26 05:06

ndreisg


iOS 14+ adds a "didReceive:replyHandler" parameter, which can contain a 'reply' object or an 'errorMessage'. This 'replyHandler' is effectively a formal implementation of the above 'evaluateJavaScript' async callback:

Apple documentation for WKScriptMessageHandlerWithReply interface and didReceive:replyHandler

For an example using this 'replyHandler', see this StackOverflow post: iOS 14 API WKScriptMessageHandlerWithReply

like image 40
Stephen Bridgett Avatar answered Jun 27 '26 03:06

Stephen Bridgett



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!