JavascriptBridge: Post a message to a parent window

Godot Version

4.3

Question

Hello everyone,
I’m trying to send a message to the parent window from the iframe of my exported godot project. A certain AI told me, that I could use JavascriptBridge to postMessage the String up to the parent window, but the eventListener there isn’t receiving anything and I don’t trust chatGPT with gdscript much.
Does anyone know if it’s this piece of code in the godot project or the event Listener that’s not working?

func onRoomEntered():
	print("Yo, you entered the room:" + roomname)
	JavaScriptBridge.eval("window.postMessage('" + roomname + "', '*');")

Thanks in advance :slight_smile:

I have the same proble, does anyone know why the postMessage doesn’t work as it should?

I’ve also tried the more elegant and not evil way, which was:

window.postMessage("done", "*")

The frontend is just not receiving the message at all.
I know the frontend works because manually calling postMessage from within the browser’s console works as it should.

extends Node

var MessageCallback: JavaScriptObject


func _ready():
	var window: JavaScriptObject = JavaScriptBridge.get_interface("window")

	MessageCallback = JavaScriptBridge.create_callback(OnMessageReceived)

	if window == null:
		#print("'window' was null when trying to create JS bridge! Not running in browser!")
		return

	window.addEventListener("message", MessageCallback)

	window.postMessage("done", "*")


func OnMessageReceived(args):
	var event = args[0]
	var data = event.data
	print(str("Received Message in-game: ", data))

Receiving the message works, and the game even receives it’s own message, but the frontend does not.

Okay I have solved it, apparently this happens when your game is running in an iframe. All you have to do is instead of doing:

jsWindow.postMessage("done", "*")

You need to post the message to the parent, like so:

jsWindow.parent.postMessage("done", "*")
1 Like