You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot中监听iframe父窗口消息问题求助

Godot中监听父窗口postMessage的问题解决

你尝试用Godot的JavaScriptBridge监听iframe中来自父窗口的message事件,第一种通过get_interface绑定回调的写法无法触发on_message_received,但直接用eval写JS监听代码却能正常运行,问题出在Godot JavaScriptBridge的回调绑定机制上。

问题原因

当你通过JavaScriptBridge.get_interface("window")获取window对象接口后,直接传入Godot创建的回调给addEventListener,这种方式存在限制:Godot侧创建的回调在JS环境中是特殊的包装对象,无法被浏览器的事件系统正确识别为有效的事件处理函数,导致事件触发时无法回调到Godot的方法。

正确实现方式

需要在JS环境中直接处理事件监听,再主动调用Godot注册的回调函数,具体代码如下:

func _ready():
    # 注册供JS调用的Godot回调函数
    JavaScriptBridge.register_callback("on_godot_message_received", on_message_received)
    
    # 通过eval添加事件监听,触发时调用注册的Godot回调
    JavaScriptBridge.eval("""
        window.addEventListener('message', (event) => {
            // 确保Godot对象和回调存在,避免报错
            if (window.Godot && typeof window.Godot.on_godot_message_received === 'function') {
                // 可以传递event的核心数据,如需验证来源可带上origin
                window.Godot.on_godot_message_received({
                    data: event.data,
                    origin: event.origin
                });
            }
        });
    """)

func on_message_received(message_info):
    print("从父窗口收到消息: ", message_info)

补充说明

  • 若只需消息内容,直接传递event.data即可;如果要防止恶意消息,可在JS或Godot侧校验event.origin是否为可信来源。
  • 复杂JS对象(如event.source)无法直接在Godot中解析,建议只传递字符串、数字或普通JSON结构的数据。

内容的提问来源于stack exchange,提问作者Cristiano Schiaffella

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:57:33