Binding javascript code to android code with objects parameters

Viewed 515

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);
1 Answers

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));
Related