简体   繁体   中英

How to call Javascript function from Kotlin code?

I am trying to compile Kotlin code as Javascript. In my code I need to encode string as URI. My 2 variants are both fail compilation:

class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
    return encodeURIComponent(str)
}

In this code compiler cannot find function encodeURIComponent(str), which according to https://www.w3schools.com/jsref/jsref_encodeuricomponent.asp is supported by all browsers.

Alternative:

class PlaceholderJS(prefix: String, placeholder: String?): Placeholder(prefix, placeholder) {
override fun encode(str: String): String {
    return URLEncoder.encode(str, Charsets.UTF_8.name())
} 

cannot find Java class URLEncoder (imported in the file as in Java). This works when compiled for JVM, but not JS.

Also I have Kotlin module marked with:

compileKotlin2Js.kotlinOptions.moduleKind = "umd"

I found that latest way to declare Javascript function in Kotlin is:

external fun encodeURIComponent(str: String): String

Once added it to the Kotlin class everything get compiled without a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM