Home > Blockchain >  Calling javascript button function from webview
Calling javascript button function from webview

Time:08-05

After creating a ‘register’ button in the webview, I want to navigate directly to a specific component when I click ‘func register’ in Kotlin.

Kotlin logic is structured like this.

// Android
inner class JavaScriptInterface
{
    @JavascriptInterface
    @SuppressWarnings("unused")
    fun register(data: String){
        navigate(
            ridday202208Ev.actionHaydxn2208EventToEventJoinForm()
        )
    }
}

This is javascript code.

 function register() {

  }

return (
 <button onClick={() => register()}></button>
)

When you click the register function in Javascript code, the webview recognizes the register function and wants to call navigate. I don't know how to deal with it.

CodePudding user response:

If you want JS to be able to execute kotlin code, you need to call addJavascriptInterface(JavaScriptInterface(), "Native") That will create an object in JS called native with all the functions your annotated on that class. Calling one of them will call directly to Kotlin or Java. Remember that you'd call Native.register(), not just register() (the object name is the second parameter to the call above, change it to whatever you want).

Remember that any function you call like this can only take null, String, or Number (int, double, etc) as parameters. You can't pass objects. You can't pass arrays (you kind of can, but you need to pass a Java array, at which point its easier to write in Java). You can't pass functions. You can work around those limitations (except functions) by passing JSON strings and serializing/deserializing them as needed.

  • Related