Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call functions in android and iOS swift from javascript in similar way

I am trying to call functions in android and iOS Swift(WKWebview)from javascript.

For Android:

public class WebAppInterface {

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void postMessage(String message) {
        Log.v(TAG, "message ----"+message);
        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();

    }
}

webView.addJavascriptInterface(new WebAppInterface(mContext), "appInterface");

JavaScript call For Android:

window.appInterface.postMessage("Hello);

Javascript call for iOS:

window.webkit.messageHandlers.appInterafce.postMeesage("Hello");

So, here we are making different calls from javascript for android and iOS. Is it possible to call functions in both android and iOS in one single way?

Thanks.

like image 410
Sindhu Avatar asked Dec 15 '17 09:12

Sindhu


1 Answers

Wrap them both up in a single function?

function postAppMessage(msg) {
    if (window.webkit != undefined) {
        if (window.webkit.messageHandlers.appInterface != undefined) {
            window.webkit.messageHandlers.appInterface.postMessage(msg)
        }
    }
    if (window.appInterface != undefined) {
        window.appInterface.postMessage(msg)
    }
}
like image 185
adamfowlerphoto Avatar answered Nov 08 '22 23:11

adamfowlerphoto