How to Achieve Type-Safe K/JS and K/Wasm Interoperability & Call Browser APIs in a Shared KMP Web Sourceset?

Hi all, how to use browser and dom api’s in a common source set containing js and wasm? I found that in both Kotlin/JS and Kotlin/Wasm there is a package named kotlinx.browser for calling browser api’s. But the fact is that the code for these two libraries is totally different. When you use a custom hierarchical project structure create a source set in the middle of wasm and js, for example:

val webMain by creating {
    dependsOn(commonMain.get())
}
wasmJsMain {
    dependsOn(webMain)
}
jsMain {
    dependsOn(webMain)
}

In fact, you can’t use any of the browser api’s in this intermediate source set, so maybe try “use expected and actual declarations” to solve this problem, but that would cause code duplication. Here’s a real-world example:

It seems possible to create a kmp library to wrap these api’s, but it would require a lot of labor or time to write a generator. In short is it too much of a hassle?


Or there is a deeper problem: could it be possible to type-safe call code from the js source set in the same kmp project in the wasm source set (runtime would put the compilation results of wasm and js together).

This also solves the same problem and brings more functionality. For example, you can use external declarations of other JS libraries from Kotlin/JS in Kotlin/Wasm, and so on.


Of course all these things can actually be implemented by rewriting some libraries or compiler plugins myself. I’m here to ask if there is an existing solution, or if there is another way to implement these features? Thanks a lot!

Hello. Currently it’s not possible, because external declarations for Js and WasmJs are not compatible (wasmJs uses JsAny). I’ve created my own module for my Kilua project, re-implementing everything with some error supressions. You can take a look at the sources and probably even use the module as a dependnecy:

I’ve opened an issue on YT: https://youtrack.jetbrains.com/issue/KT-64214

There is also ongoing effort to implement browser APIs for WasmJs in the kotlin-wrappers project:

So cool! Maybe that’s all it will have to be for now, but I noticed that Marat Akhin mentioned on YT that it might be possible to implement the feature in Kotlin 2.1, which is really exciting to see! Thank you very much for your help!