javascript_bridge.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. .. _doc_web_javascript_bridge:
  2. The JavaScriptBridge singleton
  3. ==============================
  4. In web builds, the :ref:`JavaScriptBridge <class_JavaScriptBridge>` singleton
  5. allows interaction with JavaScript and web browsers, and can be used to implement some
  6. functionalities unique to the web platform.
  7. Interacting with JavaScript
  8. ---------------------------
  9. Sometimes, when exporting Godot for the Web, it might be necessary to interface
  10. with external JavaScript code like third-party SDKs, libraries, or
  11. simply to access browser features that are not directly exposed by Godot.
  12. The ``JavaScriptBridge`` singleton provides methods to wrap a native JavaScript object into
  13. a Godot :ref:`JavaScriptObject <class_JavaScriptObject>` that tries to feel
  14. natural in the context of Godot scripting (e.g. GDScript and C#).
  15. The :ref:`JavaScriptBridge.get_interface() <class_JavaScriptBridge_method_get_interface>`
  16. method retrieves an object in the global scope.
  17. .. code-block:: gdscript
  18. extends Node
  19. func _ready():
  20. # Retrieve the `window.console` object.
  21. var console = JavaScriptBridge.get_interface("console")
  22. # Call the `window.console.log()` method.
  23. console.log("test")
  24. The :ref:`JavaScriptBridge.create_object() <class_JavaScriptBridge_method_create_object>`
  25. creates a new object via the JavaScript ``new`` constructor.
  26. .. code-block:: gdscript
  27. extends Node
  28. func _ready():
  29. # Call the JavaScript `new` operator on the `window.Array` object.
  30. # Passing 10 as argument to the constructor:
  31. # JS: `new Array(10);`
  32. var arr = JavaScriptBridge.create_object("Array", 10)
  33. # Set the first element of the JavaScript array to the number 42.
  34. arr[0] = 42
  35. # Call the `pop` function on the JavaScript array.
  36. arr.pop()
  37. # Print the value of the `length` property of the array (9 after the pop).
  38. print(arr.length)
  39. As you can see, by wrapping JavaScript objects into ``JavaScriptObject`` you can
  40. interact with them like they were native Godot objects, calling their methods,
  41. and retrieving (or even setting) their properties.
  42. Base types (int, floats, strings, booleans) are automatically converted (floats
  43. might lose precision when converted from Godot to JavaScript). Anything else
  44. (i.e. objects, arrays, functions) are seen as ``JavaScriptObjects`` themselves.
  45. Callbacks
  46. ---------
  47. Calling JavaScript code from Godot is nice, but sometimes you need to call a
  48. Godot function from JavaScript instead.
  49. This case is a bit more complicated. JavaScript relies on garbage collection,
  50. while Godot uses reference counting for memory management. This means you have
  51. to explicitly create callbacks (which are returned as ``JavaScriptObjects``
  52. themselves) and you have to keep their reference.
  53. Arguments passed by JavaScript to the callback will be passed as a single Godot
  54. ``Array``.
  55. .. code-block:: gdscript
  56. extends Node
  57. # Here we create a reference to the `_my_callback` function (below).
  58. # This reference will be kept until the node is freed.
  59. var _callback_ref = JavaScriptBridge.create_callback(_my_callback)
  60. func _ready():
  61. # Get the JavaScript `window` object.
  62. var window = JavaScriptBridge.get_interface("window")
  63. # Set the `window.onbeforeunload` DOM event listener.
  64. window.onbeforeunload = _callback_ref
  65. func _my_callback(args):
  66. # Get the first argument (the DOM event in our case).
  67. var js_event = args[0]
  68. # Call preventDefault and set the `returnValue` property of the DOM event.
  69. js_event.preventDefault()
  70. js_event.returnValue = ''
  71. .. warning::
  72. Callback methods created via :ref:`JavaScriptBridge.get_interface() <class_JavaScriptBridge_method_get_interface>`
  73. (``_my_callback`` in the above example) **must** take exactly one :ref:`Array<class_Array>`
  74. argument, which is going to be the JavaScript `arguments object <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments>`__
  75. converted to an array. Otherwise, the callback method will not be called.
  76. Here is another example that asks the user for the `Notification permission <https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API>`__
  77. and waits asynchronously to deliver a notification if the permission is
  78. granted:
  79. .. code-block:: gdscript
  80. extends Node
  81. # Here we create a reference to the `_on_permissions` function (below).
  82. # This reference will be kept until the node is freed.
  83. var _permission_callback = JavaScriptBridge.create_callback(_on_permissions)
  84. func _ready():
  85. # NOTE: This is done in `_ready` for simplicity, but SHOULD BE done in response
  86. # to user input instead (e.g. during `_input`, or `button_pressed` event, etc.),
  87. # otherwise it might not work.
  88. # Get the `window.Notification` JavaScript object.
  89. var notification = JavaScriptBridge.get_interface("Notification")
  90. # Call the `window.Notification.requestPermission` method which returns a JavaScript
  91. # Promise, and bind our callback to it.
  92. notification.requestPermission().then(_permission_callback)
  93. func _on_permissions(args):
  94. # The first argument of this callback is the string "granted" if the permission is granted.
  95. var permission = args[0]
  96. if permission == "granted":
  97. print("Permission granted, sending notification.")
  98. # Create the notification: `new Notification("Hi there!")`
  99. JavaScriptBridge.create_object("Notification", "Hi there!")
  100. else:
  101. print("No notification permission.")
  102. Can I use my favorite library?
  103. ------------------------------
  104. You most likely can. First, you have to
  105. include your library in the page. You can customize the
  106. :ref:`Head Include <doc_javascript_export_options>` during export (see below),
  107. or even :ref:`write your own template <doc_customizing_html5_shell>`.
  108. In the example below, we customize the ``Head Include`` to add an external library
  109. (`axios <https://axios-http.com/>`__) from a content delivery network, and a
  110. second ``<script>`` tag to define our own custom function:
  111. .. code-block:: html
  112. <!-- Axios -->
  113. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  114. <!-- Custom function -->
  115. <script>
  116. function myFunc() {
  117. alert("My func!");
  118. }
  119. </script>
  120. We can then access both the library and the function from Godot, like we did in
  121. previous examples:
  122. .. code-block:: gdscript
  123. extends Node
  124. # Here create a reference to the `_on_get` function (below).
  125. # This reference will be kept until the node is freed.
  126. var _callback = JavaScriptBridge.create_callback(_on_get)
  127. func _ready():
  128. # Get the `window` object, where globally defined functions are.
  129. var window = JavaScriptBridge.get_interface("window")
  130. # Call the JavaScript `myFunc` function defined in the custom HTML head.
  131. window.myFunc()
  132. # Get the `axios` library (loaded from a CDN in the custom HTML head).
  133. var axios = JavaScriptBridge.get_interface("axios")
  134. # Make a GET request to the current location, and receive the callback when done.
  135. axios.get(window.location.toString()).then(_callback)
  136. func _on_get(args):
  137. OS.alert("On Get")
  138. The eval interface
  139. ------------------
  140. The ``eval`` method works similarly to the JavaScript function of the same
  141. name. It takes a string as an argument and executes it as JavaScript code.
  142. This allows interacting with the browser in ways not possible with script
  143. languages integrated into Godot.
  144. .. tabs::
  145. .. code-tab:: gdscript
  146. func my_func():
  147. JavaScriptBridge.eval("alert('Calling JavaScript per GDScript!');")
  148. .. code-tab:: csharp
  149. private void MyFunc()
  150. {
  151. JavaScriptBridge.Eval("alert('Calling JavaScript per C#!');")
  152. }
  153. The value of the last JavaScript statement is converted to a GDScript value and
  154. returned by ``eval()`` under certain circumstances:
  155. * JavaScript ``number`` is returned as :ref:`class_float`
  156. * JavaScript ``boolean`` is returned as :ref:`class_bool`
  157. * JavaScript ``string`` is returned as :ref:`class_String`
  158. * JavaScript ``ArrayBuffer``, ``TypedArray``, and ``DataView`` are returned as :ref:`PackedByteArray<class_PackedByteArray>`
  159. .. tabs::
  160. .. code-tab:: gdscript
  161. func my_func2():
  162. var js_return = JavaScriptBridge.eval("var myNumber = 1; myNumber + 2;")
  163. print(js_return) # prints '3.0'
  164. .. code-tab:: csharp
  165. private void MyFunc2()
  166. {
  167. var jsReturn = JavaScriptBridge.Eval("var myNumber = 1; myNumber + 2;");
  168. GD.Print(jsReturn); // prints '3.0'
  169. }
  170. Any other JavaScript value is returned as ``null``.
  171. HTML5 export templates may be :ref:`built <doc_compiling_for_web>` without
  172. support for the singleton to improve security. With such templates, and on
  173. platforms other than HTML5, calling ``JavaScriptBridge.eval`` will also return
  174. ``null``. The availability of the singleton can be checked with the
  175. ``web`` :ref:`feature tag <doc_feature_tags>`:
  176. .. tabs::
  177. .. code-tab:: gdscript
  178. func my_func3():
  179. if OS.has_feature('web'):
  180. JavaScriptBridge.eval("""
  181. console.log('The JavaScriptBridge singleton is available')
  182. """)
  183. else:
  184. print("The JavaScriptBridge singleton is NOT available")
  185. .. code-tab:: csharp
  186. private void MyFunc3()
  187. {
  188. if (OS.HasFeature("web"))
  189. {
  190. JavaScriptBridge.Eval("console.log('The JavaScriptBridge singleton is available')");
  191. }
  192. else
  193. {
  194. GD.Print("The JavaScriptBridge singleton is NOT available");
  195. }
  196. }
  197. .. tip:: GDScript's multi-line strings, surrounded by 3 quotes ``"""`` as in
  198. ``my_func3()`` above, are useful to keep JavaScript code readable.
  199. The ``eval`` method also accepts a second, optional Boolean argument, which
  200. specifies whether to execute the code in the global execution context,
  201. defaulting to ``false`` to prevent polluting the global namespace:
  202. .. tabs::
  203. .. code-tab:: gdscript
  204. func my_func4():
  205. # execute in global execution context,
  206. # thus adding a new JavaScript global variable `SomeGlobal`
  207. JavaScriptBridge.eval("var SomeGlobal = {};", true)
  208. .. code-tab:: csharp
  209. private void MyFunc4()
  210. {
  211. // execute in global execution context,
  212. // thus adding a new JavaScript global variable `SomeGlobal`
  213. JavaScriptBridge.Eval("var SomeGlobal = {};", true);
  214. }
  215. .. _doc_web_downloading_files:
  216. Downloading files
  217. -----------------
  218. 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
  219. very common use case, Godot exposes this functionality to scripting via
  220. a dedicated :ref:`JavaScriptBridge.download_buffer() <class_JavaScriptBridge_method_download_buffer>`
  221. function which lets you download any generated buffer.
  222. Here is a minimal example on how to use it:
  223. extends Node
  224. .. code-block:: gdscript
  225. func _ready():
  226. # Asks the user download a file called "hello.txt" whose content will be the string "Hello".
  227. JavaScriptBridge.download_buffer("Hello".to_utf8_buffer(), "hello.txt")
  228. And here is a more complete example on how to download a previously saved file:
  229. .. code-block:: gdscript
  230. extends Node
  231. # Open a file for reading and download it via the JavaScript singleton.
  232. func _download_file(path):
  233. var file = FileAccess.open(path, FileAccess.READ)
  234. if file == null:
  235. push_error("Failed to load file")
  236. return
  237. # Get the file name.
  238. var fname = path.get_file()
  239. # Read the whole file to memory.
  240. var buffer = file.get_buffer(file.get_len())
  241. # Prompt the user to download the file (will have the same name as the input file).
  242. JavaScriptBridge.download_buffer(buffer, fname)
  243. func _ready():
  244. # Create a temporary file.
  245. var config = ConfigFile.new()
  246. config.set_value("option", "one", false)
  247. config.save("/tmp/test.cfg")
  248. # Download it
  249. _download_file("/tmp/test.cfg")