10

As the title suggests, I'm trying to bind javascript code to my android app so I can react in my app to an event/message that my website is sending.

After reading the official android documentation related to javascript binding I managed to easily implement it.. as long as it's a string.

What is working fine? I implemented the following code in my app:

/** Instantiate the interface and set the context  */
class ClientInterface(private val mContext: Context) {

    /** Show a toast from the web page  */
    @JavascriptInterface
    fun postMessage(message: String) {
        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show()
    }
}

if the parameter of the 'postMessage' function is a String and I'm passing a String from my javascript as a parameter, everything is fine. it's passing the string. my problem is that I am trying to get a JSONObject instead of a String, and it's not working. I tried casting everything I thought might work.. JSONObject / JSONObject? / Any / Any? / Object / Object? and so on..

when I'm sending an object on my javascript, nothing seems to work. all I get in my app is a null response.

anyone ever tried something like that? what am I missing?

P.S - here's my javascript code for reference:

var objectMessage = {
        type: "quote",
        code: "My name is Inigo Montoya. You killed my father, prepare to die!"
    }

window.CLIENT.postMessage(objectMessage);
3
  • try to return Json object from javascript with JSON.stringify(obj); and receive it as string on your Android code, then parse it to your object. Commented Jun 17, 2019 at 13:00
  • Did you register the ClientInterface class as JSInterface in the webview? Commented Jun 17, 2019 at 13:14
  • @TheDude Yup. I did. Commented Jun 17, 2019 at 13:30

1 Answer 1

3

You can't pass an object only primitive! So you need to stringify your object.

var objectMessage = {
  type: "quote",
  code: "My name is Inigo Montoya. You killed my father, prepare to die!"
}

window.CLIENT.postMessage(JSON.stringify(objectMessage));
Sign up to request clarification or add additional context in comments.

2 Comments

Are you sure it's not possible? Is it written anywhere? documented somewhere?
Yes i'm sure, try it.

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.