Calling a Godot Function from JavaScript with Parameters (Godot 4)

Hello Godot community,

I’m working on a Godot 4 project and need assistance with calling a Godot function from JavaScript.

My code

func UpdateFTMS(json_str):
	var json = JSON.new()
	var data = json.parse(json_str)

	if "Cadence" in data:
		Cadence = data.Cadence
	if "Power" in data:
		Power = data.Power
	if "HRM" in data:
		HRM = data.HRM
	if "FTP" in data:
		FTP = data.FTP

Could someone please provide a simple example or guide me on the correct syntax for calling a Godot function from JavaScript with parameters?

Thank you for your assistance!

You can use the JavaScriptBridge interface to communicate with JavaScript.

For example, create a global object in JavaScript with JavaScriptBridge.eval() that exposes a way to attach a callback to a function. Create a callback to GDScript code with JavaScriptBridge.create_callback() Then get that global object you created with JavaScriptBridge.get_interface() and set that callback to the JavaScript callback.

Every time you call the object that uses that callback the Godot side will receive it. Only a few JavaScript types are converted to Godot Variants so it’s better to create a json string to communicate between. The types that can be converted are in this page Exporting for the Web — Godot Engine (stable) documentation in English

Example:

extends Node


var my_callback = JavaScriptBridge.create_callback(_on_my_callback)


func _init() -> void:
	JavaScriptBridge.eval("""
var godotBridge = {
	callback: null,
	setCallback: (cb) => this.callback = cb,
	test: (data) => this.callback(JSON.stringify(data)),
};
	""", true)
	var godot_bridge = JavaScriptBridge.get_interface("godotBridge")
	godot_bridge.setCallback(my_callback)


func _on_my_callback(args) -> void:
	printt('this is coming from js: ', args)

i got a error how to fix
Attempt to call function ‘setCallback’ in base ‘null instance’ on a null instance.

extends Node2D

var my_callback = JavaScriptBridge.create_callback(_on_my_callback)


func _init() -> void:
	JavaScriptBridge.eval("""
var godotBridge = {
	callback: null,
	setCallback: (cb) => this.callback = cb,
	test: (data) => this.callback(JSON.stringify(data)),
};
	""", true)
	var godot_bridge = JavaScriptBridge.get_interface("godotBridge")
	godot_bridge.setCallback(my_callback)


func _on_my_callback(args) -> void:
	var data = JSON.parse_string(args)
	if "Cadence" in data:
		Cadence = data.Cadence
	if "Power" in data:
		Power = data.Power
	if "HRM" in data:
		HRM = data.HRM
	if "FTP" in data:
		FTP = data.FTP

I’m not sure. You need to run it in the browser or it won’t work.

To test it in the browser add an HTML5 export preset and the Remote Debug button should appear. Like this:

Remote Debug Button