如何通过 window.addEventListener 使用 MessageEventInit

How to use MessageEventInit with window.addEventListener

我正在尝试使用 kotlin-js 注册网络消息频道,但无法确定如何访问 MessageEventInit 类型。

https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom/-message-event-init/index.html

window.addEventListener 方法仅公开通用 Event 类型

https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom.events/-event-target/add-event-listener.html

fun addEventListener(
    type: String,
    callback: EventListener?,
    options: dynamic = definedExternally)
fun addEventListener(
    type: String,
    callback: ((Event) -> Unit)?,
    options: dynamic = definedExternally)

这是我到目前为止的想法,但是我很难构建这个项目。

fun configureChannel() {
    val channel = MessageChannel()
    var jsPortOne = channel.port1
    var jsPortTwo = channel.port2

    window.addEventListener("message", {
    }, false)

    jsPortOne.addEventListener("message", {
        window.alert((it as MessageEvent).data.toString())
    }, false)

    jsPortTwo.addEventListener("message", {
        window.alert((it as MessageEvent).data.toString())
    }, false)

    jsPortOne.start()
    jsPortTwo.start()
}

我的主要目标是将此文件转换为 Kotlin/JS 并将其与此 kotlin android 项目合并

https://github.com/darran-kelinske-fivestars/cordova-alternative-pattern/blob/master/app/src/main/assets/js/index.js

预感是正确的。我能够构建和部署项目。要在 Kotlin/JS 中使用 MessageEvent 类型,您需要将事件转换为 MessageEvent

val event = it as MessageEvent

这是一个示例:

@JsName("configureChannel")
fun configureChannel() {
    console.log("Configuring channel")
    window.addEventListener("message", {

        val event = it as MessageEvent

        if (event.data != KEY_CAPTURE_PORT) {
            console.log("event.data: ${event.data}")
            inputPort.postMessage(event.data)
        } else if (event.data == KEY_CAPTURE_PORT) {
            console.log("assigning captured port")
            outputPort = event.ports[0]
        }
    }, false)

    inputPort.start()
    outputPort.start()
}