kotlinkotlin-multiplatformkotlin-js

window.getSelection() in Kotlin/JS


There is window.getSelection() in JS. What is the equivalent in Kotlin/JS? There is nothing in Kotlin Window API.


Solution

  • Note that it is present in the kotlin-browser module from the official kotlin-wrappers.

    Instead of importing kotlinx.browser.window, use web.window.window:

    import web.window.window
    
    val selection = window.getSelection() ?: error("no selection")
    

    Also, in general, if something is missing in Kotlin/JS types but you know the actual object has the method or property you need, you can always "force" your way by using asDynamic():

    import kotlinx.browser.window
    
    val selection = window.asDynamic().getSelection() ?: error("no selection")
    

    But this gives up type checking for the return value too.