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);
Bind JavaScript code to Android code Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript, and the method must be public.
A binding in JavaScript is the formal terminology for what a lot of people refer to as a variable. In ES2015+, a variable can be defined with the let keyword, but you can also define constant with the const keyword. A binding could refer to either a variable or a constant.
Can we use JavaScript for Android? Yes, of course! The Android ecosystem supports the concept of hybrid apps, which is a wrapper over the native platform.
We need to enable JavaScript in a WebView. To achieve this, we must go to the web settings in our WebView. Then, we can retrieve WebSettings with getSettings() and finally enable JavaScript with setJavaScriptEnabled(). In your Activity/Fragment class , we enable JavaScript by assigning it to a boolean value as “true”.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With