Godot Version
3.6
Question
I am creating a Godot game that is embedded in an HTML page. I want to be able to call a Godot function from JavaScript (on the click of a button). I am having trouble getting my code to work.
Here is my GDscript code (RobotController.gd):
extends Spatial
var robot
func _ready() -> void:
print("init")
robot = get_node("../Robot")
var callback = JavaScript.create_callback(self, "receivedMessage")
if OS.has_feature("JavaScript"):
print("has js")
var window = JavaScript.get_interface("window")
window.onmessage = callback
else:
print("no js")
func receivedMessage(args):
print ("recieved message")
robot.moveForward()
# parse
var key
if args[0].message:
key = 'message'
else:
key = 'data'
var data = args[0][key]
# filter
if data.find('toGodot:') == 0:
# message starts with 'toGodot:'
data = data.replace('toGodot:', '')
if (data == "moveForward"):
robot.moveForward()
My HTML file containing my JavaScript code (index.html) is:
<!DOCTYPE html>
<html>
<head>
<title>Test Godot</title>
<meta charset="UTF-8">
</head>
<body>
<iframe id="canvas" src="godot.html" style="width: 50%; height: 300px; border: 1px solid black;"></iframe>
<button id="moveForwardButton" onclick="moveForward()">Move Forward</button>
<script src="godot.js"></script>
<script>
var iframe = document.getElementById("canvas");
var gdBase = "toGodot:";
function moveForward(){
//console.log("clicked");
iframe.contentWindow.postMessage(gdBase + 'moveForward', '*');
}
</script>
</body>
</html>
I am having a lot of trouble getting Godot to receive the message. I based my code off of a solution here, but am unable to get it to work. Any help/advice is appreciated. Thanks in advance!