I'm making my first steps in android webapp development.
I wrote some android functions and made them accessible to javascript, it works like a charm (set pref, read pref...).
My question: is it possible to declare default value for function arguments?
As an illustration:
showToast()
hereunder is available from within javadcript in the WebView webView1.
But it can't be called with a single argument (lengthLong: Boolean = true
seems to have no effect js-side).
class CallableFromWebViewJS(context: Context) {
private val context: Context
init {
this.context= context
}
@JavascriptInterface
fun showToast(message: String?, lengthLong: Boolean = true) {
Toast.makeText(context, message, if (lengthLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT)
.show()
}
}
...
/* Then somewhere in my main activity: */
webView1.addJavascriptInterface(CallableFromWebViewJS(this), "appInterface");
In the JS script:
appInterface.showToast("Foo bar", true); //this works
appInterface.showToast("Foo bar"); //this does NOT work
Can I achieve this, and if yes, how?
CodePudding user response:
You can force Android JavascriptInterface interpreter to create both javascript methods like the code below.
@JavascriptInterface
fun showToast(message: String?) {
// here, you can define the default value
showToast(message, true)
}
@JavascriptInterface
fun showToast(message: String?, lengthLong: Boolean) {
Toast.makeText(
context,
message,
if (lengthLong) Toast.LENGTH_LONG else Toast.LENGTH_SHORT
)
.show()
}
If you need to send complex data you can use simply json
.
const someObject = {
message: "hello world",
isLong: false,
}
const toSend = JSON.stringify(someObject);
// send to Android web interface
appInterface.complex(toSend);
@JavascriptInterface
fun complex(jsonStr: String) {
val json = JSONObject(jsonStr)
println(json.getString("message"))
println(json.getBoolean("isLong"))
// or use as you want
}
Hope it helps