18

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.

1 Answer 1

33

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)
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I spent a whole day to find this simple answer for my same need. You saved my second day.
whats the swift equivalent for postMessage function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.