The JavaScriptBridge Singleton

In web builds, the JavaScriptBridge singleton allows interaction with JavaScript and web browsers, and can be used to implement some functionalities unique to the web platform.

Interacting with JavaScript

Sometimes, when exporting Godot for the Web, it might be necessary to interface with external JavaScript code like third-party SDKs, libraries, or simply to access browser features that are not directly exposed by Godot.

The JavaScriptBridge singleton provides methods to wrap a native JavaScript object into a Godot JavaScriptObject that tries to feel natural in the context of Godot scripting (e.g. GDScript and C#).

The JavaScriptBridge.get_interface() method retrieves an object in the global scope.

  1. extends Node
  2. func _ready():
  3. # Retrieve the `window.console` object.
  4. var console = JavaScriptBridge.get_interface("console")
  5. # Call the `window.console.log()` method.
  6. console.log("test")

The JavaScriptBridge.create_object() creates a new object via the JavaScript new constructor.

  1. extends Node
  2. func _ready():
  3. # Call the JavaScript `new` operator on the `window.Array` object.
  4. # Passing 10 as argument to the constructor:
  5. # JS: `new Array(10);`
  6. var arr = JavaScriptBridge.create_object("Array", 10)
  7. # Set the first element of the JavaScript array to the number 42.
  8. arr[0] = 42
  9. # Call the `pop` function on the JavaScript array.
  10. arr.pop()
  11. # Print the value of the `length` property of the array (9 after the pop).
  12. print(arr.length)

As you can see, by wrapping JavaScript objects into JavaScriptObject you can interact with them like they were native Godot objects, calling their methods, and retrieving (or even setting) their properties.

Base types (int, floats, strings, booleans) are automatically converted (floats might lose precision when converted from Godot to JavaScript). Anything else (i.e. objects, arrays, functions) are seen as JavaScriptObjects themselves.

Callbacks

Calling JavaScript code from Godot is nice, but sometimes you need to call a Godot function from JavaScript instead.

This case is a bit more complicated. JavaScript relies on garbage collection, while Godot uses reference counting for memory management. This means you have to explicitly create callbacks (which are returned as JavaScriptObjects themselves) and you have to keep their reference.

Arguments passed by JavaScript to the callback will be passed as a single Godot Array.

  1. extends Node
  2. # Here we create a reference to the `_my_callback` function (below).
  3. # This reference will be kept until the node is freed.
  4. var _callback_ref = JavaScriptBridge.create_callback(_my_callback)
  5. func _ready():
  6. # Get the JavaScript `window` object.
  7. var window = JavaScriptBridge.get_interface("window")
  8. # Set the `window.onbeforeunload` DOM event listener.
  9. window.onbeforeunload = _callback_ref
  10. func _my_callback(args):
  11. # Get the first argument (the DOM event in our case).
  12. var js_event = args[0]
  13. # Call preventDefault and set the `returnValue` property of the DOM event.
  14. js_event.preventDefault()
  15. js_event.returnValue = ''

Here is another example that asks the user for the Notification permission and waits asynchronously to deliver a notification if the permission is granted:

  1. extends Node
  2. # Here we create a reference to the `_on_permissions` function (below).
  3. # This reference will be kept until the node is freed.
  4. var _permission_callback = JavaScriptBridge.create_callback(_on_permissions)
  5. func _ready():
  6. # NOTE: This is done in `_ready` for simplicity, but SHOULD BE done in response
  7. # to user input instead (e.g. during `_input`, or `button_pressed` event, etc.),
  8. # otherwise it might not work.
  9. # Get the `window.Notification` JavaScript object.
  10. var notification = JavaScriptBridge.get_interface("Notification")
  11. # Call the `window.Notification.requestPermission` method which returns a JavaScript
  12. # Promise, and bind our callback to it.
  13. notification.requestPermission().then(_permission_callback)
  14. func _on_permissions(args):
  15. # The first argument of this callback is the string "granted" if the permission is granted.
  16. var permission = args[0]
  17. if permission == "granted":
  18. print("Permission granted, sending notification.")
  19. # Create the notification: `new Notification("Hi there!")`
  20. JavaScriptBridge.create_object("Notification", "Hi there!")
  21. else:
  22. print("No notification permission.")

Can I use my favorite library?

You most likely can. First, you have to include your library in the page. You can simply customize the Head Include during export (see below), or even write your own template.

In the example below, we customize the Head Include to add an external library (axios) from a content delivery network, and a second <script> tag to define our own custom function:

  1. <!-- Axios -->
  2. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  3. <!-- Custom function -->
  4. <script>
  5. function myFunc() {
  6. alert("My func!");
  7. }
  8. </script>

We can then access both the library and the function from Godot, like we did in previous examples:

  1. extends Node
  2. # Here create a reference to the `_on_get` function (below).
  3. # This reference will be kept until the node is freed.
  4. var _callback = JavaScriptBridge.create_callback(_on_get)
  5. func _ready():
  6. # Get the `window` object, where globally defined functions are.
  7. var window = JavaScriptBridge.get_interface("window")
  8. # Call the JavaScript `myFunc` function defined in the custom HTML head.
  9. window.myFunc()
  10. # Get the `axios` library (loaded from a CDN in the custom HTML head).
  11. var axios = JavaScriptBridge.get_interface("axios")
  12. # Make a GET request to the current location, and receive the callback when done.
  13. axios.get(window.location.toString()).then(_callback)
  14. func _on_get(args):
  15. OS.alert("On Get")

The eval interface

The eval method works similarly to the JavaScript function of the same name. It takes a string as an argument and executes it as JavaScript code. This allows interacting with the browser in ways not possible with script languages integrated into Godot.

GDScriptC#

  1. func my_func():
  2. JavaScriptBridge.eval("alert('Calling JavaScript per GDScript!');")
  1. private void MyFunc()
  2. {
  3. JavaScriptBridge.Eval("alert('Calling JavaScript per C#!');")
  4. }

最后一个JavaScript语句的值转换为GDScript值,并在某些情况下由 eval() 返回:

  • JavaScript number 会以 float 返回

  • JavaScript boolean 会以 bool 返回

  • JavaScript string 会以 String 返回

  • JavaScript ArrayBuffer, TypedArray, and DataView are returned as PackedByteArray

GDScriptC#

  1. func my_func2():
  2. var js_return = JavaScriptBridge.eval("var myNumber = 1; myNumber + 2;")
  3. print(js_return) # prints '3.0'
  1. private void MyFunc2()
  2. {
  3. var jsReturn = JavaScriptBridge.Eval("var myNumber = 1; myNumber + 2;");
  4. GD.Print(jsReturn); // prints '3.0'
  5. }

任何其他JavaScript值都返回为 null .

HTML5 export templates may be built without support for the singleton to improve security. With such templates, and on platforms other than HTML5, calling JavaScriptBridge.eval will also return null. The availability of the singleton can be checked with the web feature tag:

GDScriptC#

  1. func my_func3():
  2. if OS.has_feature('web'):
  3. JavaScriptBridge.eval("""
  4. console.log('The JavaScriptBridge singleton is available')
  5. """)
  6. else:
  7. print("The JavaScriptBridge singleton is NOT available")
  1. private void MyFunc3()
  2. {
  3. if (OS.HasFeature("web"))
  4. {
  5. JavaScriptBridge.Eval("console.log('The JavaScriptBridge singleton is available')");
  6. }
  7. else
  8. {
  9. GD.Print("The JavaScriptBridge singleton is NOT available");
  10. }
  11. }

小技巧

GDScript中的多行字符串由3双引号 """ 包围, 如同上文中的 my_func3() 那样, 有助于保证JavaScript代码的可读性.

The eval method also accepts a second, optional Boolean argument, which specifies whether to execute the code in the global execution context, defaulting to false to prevent polluting the global namespace:

GDScriptC#

  1. func my_func4():
  2. # execute in global execution context,
  3. # thus adding a new JavaScript global variable `SomeGlobal`
  4. JavaScriptBridge.eval("var SomeGlobal = {};", true)
  1. private void MyFunc4()
  2. {
  3. // execute in global execution context,
  4. // thus adding a new JavaScript global variable `SomeGlobal`
  5. JavaScriptBridge.Eval("var SomeGlobal = {};", true);
  6. }

Downloading files

Downloading files (e.g. a save game) from the Godot Web export to the user’s computer can be done by directly interacting with JavaScript, but given it is a very common use case, Godot exposes this functionality to scripting via a dedicated JavaScriptBridge.download_buffer() function which lets you download any generated buffer.

Here is a minimal example on how to use it:

extends Node

  1. func _ready():
  2. # Asks the user download a file called "hello.txt" whose content will be the string "Hello".
  3. JavaScriptBridge.download_buffer("Hello".to_utf8_buffer(), "hello.txt")

And here is a more complete example on how to download a previously saved file:

  1. extends Node
  2. # Open a file for reading and download it via the JavaScript singleton.
  3. func _download_file(path):
  4. var file = FileAccess.open(path, FileAccess.READ)
  5. if file == null:
  6. push_error("Failed to load file")
  7. return
  8. # Get the file name.
  9. var fname = path.get_file()
  10. # Read the whole file to memory.
  11. var buffer = file.get_buffer(file.get_len())
  12. # Prompt the user to download the file (will have the same name as the input file).
  13. JavaScriptBridge.download_buffer(buffer, fname)
  14. func _ready():
  15. # Create a temporary file.
  16. var config = ConfigFile.new()
  17. config.set_value("option", "one", false)
  18. config.save("/tmp/test.cfg")
  19. # Download it
  20. _download_file("/tmp/test.cfg")