kotlingoogle-signinkotlin-multiplatformkotlin-js

How to integrate Google GSI with Kotlin/JS


Am trying to implement Google on-tap sign-in in a Kotlin/Js project.

Is there any kotlin-wrapper like library available to use https://accounts.google.com/gsi/client in a Kotlin/Js project?

Or is there any reference on how this can be done?

I tried this -

In my index.html, as per gsi docs

<script src="https://accounts.google.com/gsi/client" async defer></script>

And in kotlin/Js react app

val google: dynamic = window.asDynamic().google

val SignIn =
    FC<Props> {    
        useEffect {      
            google.accounts.id.initialize()
    }
 }

But I get this error on browser

Unexpected Application Error!

Cannot read properties of undefined (reading 'accounts')


Solution

  • The problem is that you immediately trying to access window.google, when google client script hasn't been loaded. async and defer attributes ensure that script will be loaded asynchroniusly after document has been parsed. So when this line

    val google: dynamic = window.asDynamic().google
    

    is executing, it is always null.

    I suggest you change it to this line:

    val google: dynamic get() = window.asDynamic().google
    

    In that case you will access window.google on demand.