Sunday, August 8, 2021

iOS WKWebView passing javascript

<script>

    $(function() {

        var tokenInfo = $("#TokenInfo").val();

        try {

            window.webkit.messageHandlers.scriptHandler.postMessage(tokenInfo); // For iOS

        } catch (e) {

            //

        } 

        try {

            Android.login(tokenInfo); // For Android

        } catch (e) {

            //

        }

    })

</script>


Store your JSON data in a hidden field as a string in your html file.


<input id="TokenInfo" type="hidden" value="YOUR_JSON_DATA"/>

Add following javaScript Code into your html page.


<script>

    $(function() {

        var tokenInfo = $("#TokenInfo").val();

        try {

            window.webkit.messageHandlers.scriptHandler.postMessage(tokenInfo); // For iOS

        } catch (e) {

            //

        } 

        try {

            Android.login(tokenInfo); // For Android

        } catch (e) {

            //

        }

    })

</script>

From android end you need to add a JavaScriptInterface interface into to web view

final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(getContext());

webview.addJavascriptInterface(myJavaScriptInterface, "Android");


public class JavaScriptInterface {

    Context mContext;


    JavaScriptInterface(Context c) {

        mContext = c;

    }


    @JavascriptInterface

    public void login(String tokenInfo) {

        // deserialize your json here.

    }

}



But the above wasn't working well from React JS. 


References:

https://stackoverflow.com/questions/60093612/get-json-values-from-webview




No comments:

Post a Comment