exporting_for_web.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. .. _doc_exporting_for_web:
  2. Exporting for the Web
  3. =====================
  4. .. seealso::
  5. This page describes how to export a Godot project to HTML5.
  6. If you're looking to compile editor or export template binaries from source instead,
  7. read :ref:`doc_compiling_for_web`.
  8. HTML5 export allows publishing games made in Godot Engine to the browser.
  9. This requires support for `WebAssembly
  10. <https://webassembly.org/>`__, `WebGL <https://www.khronos.org/webgl/>`__ and
  11. `SharedArrayBuffer <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer>`_
  12. in the user's browser.
  13. .. important:: Use the browser-integrated developer console, usually opened
  14. with :kbd:`F12`, to view **debug information** like JavaScript,
  15. engine, and WebGL errors.
  16. .. attention::
  17. Godot 4's HTML5 exports currently cannot run on macOS and iOS due to upstream bugs
  18. with SharedArrayBuffer and WebGL 2.0. We recommend using
  19. :ref:`macOS <doc_exporting_for_macos>` and :ref:`iOS <doc_exporting_for_ios>`
  20. native export functionality instead, as it will also result in better performance.
  21. Godot 3's HTML5 exports are more compatible with various browsers in
  22. general, especially when using the GLES2 rendering backend (which only
  23. requires WebGL 1.0).
  24. .. warning:: SharedArrayBuffer requires a :ref:`secure context <doc_javascript_secure_contexts>`.
  25. Browsers also require that the web page is served with specific
  26. `cross-origin isolation headers <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy>`__.
  27. .. note::
  28. If you use Linux, due to
  29. `poor Firefox WebGL performance <https://bugzilla.mozilla.org/show_bug.cgi?id=1010527>`__,
  30. it's recommended to play the exported project using a Chromium-based browser
  31. instead of Firefox.
  32. WebGL version
  33. -------------
  34. Godot 4.0 and later can only target WebGL 2.0 (using the Compatibility rendering
  35. method). There is no stable way to run Vulkan applications on the web yet.
  36. See `Can I use WebGL 2.0 <https://caniuse.com/webgl2>`__ for a list of browser
  37. versions supporting WebGL 2.0. Note that Safari has several issues with WebGL
  38. 2.0 support that other browsers don't have, so we recommend using a
  39. Chromium-based browser or Firefox if possible.
  40. .. _doc_javascript_export_options:
  41. Export options
  42. --------------
  43. If a runnable web export template is available, a button appears between the
  44. *Stop scene* and *Play edited Scene* buttons in the editor to quickly open the
  45. game in the default browser for testing.
  46. If you plan to use :ref:`VRAM compression <doc_importing_images>` make sure that
  47. **Vram Texture Compression** is enabled for the targeted platforms (enabling
  48. both **For Desktop** and **For Mobile** will result in a bigger, but more
  49. compatible export).
  50. If a path to a **Custom HTML shell** file is given, it will be used instead of
  51. the default HTML page. See :ref:`doc_customizing_html5_shell`.
  52. **Head Include** is appended into the ``<head>`` element of the generated
  53. HTML page. This allows to, for example, load webfonts and third-party
  54. JavaScript APIs, include CSS, or run JavaScript code.
  55. .. important:: Each project must generate their own HTML file. On export,
  56. several text placeholders are replaced in the generated HTML
  57. file specifically for the given export options. Any direct
  58. modifications to that HTML file will be lost in future exports.
  59. To customize the generated file, use the **Custom HTML shell**
  60. option.
  61. Limitations
  62. -----------
  63. For security and privacy reasons, many features that work effortlessly on
  64. native platforms are more complicated on the web platform. Following is a list
  65. of limitations you should be aware of when porting a Godot game to the web.
  66. .. _doc_javascript_secure_contexts:
  67. .. important:: Browser vendors are making more and more functionalities only
  68. available in `secure contexts <https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts>`_,
  69. this means that such features are only be available if the web
  70. page is served via a secure HTTPS connection (localhost is
  71. usually exempt from such requirement).
  72. .. tip:: Check the `list of open HTML5 issues on GitHub
  73. <https://github.com/godotengine/godot/issues?q=is:open+is:issue+label:platform:html5>`__
  74. to see if the functionality you're interested in has an issue yet. If
  75. not, open one to communicate your interest.
  76. Using cookies for data persistence
  77. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  78. Users must **allow cookies** (specifically IndexedDB) if persistence of the
  79. ``user://`` file system is desired. When playing a game presented in an
  80. ``iframe``, **third-party** cookies must also be enabled. Incognito/private
  81. browsing mode also prevents persistence.
  82. The method ``OS.is_userfs_persistent()`` can be used to check if the
  83. ``user://`` file system is persistent, but can give false positives in some
  84. cases.
  85. Background processing
  86. ~~~~~~~~~~~~~~~~~~~~~
  87. The project will be paused by the browser when the tab is no longer the active
  88. tab in the user's browser. This means functions such as ``_process()`` and
  89. ``_physics_process()`` will no longer run until the tab is made active again by
  90. the user (by switching back to the tab). This can cause networked games to
  91. disconnect if the user switches tabs for a long duration.
  92. This limitation does not apply to unfocused browser *windows*. Therefore, on the
  93. user's side, this can be worked around by running the project in a separate
  94. *window* instead of a separate tab.
  95. Full screen and mouse capture
  96. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. Browsers do not allow arbitrarily **entering full screen**. The same goes for
  98. **capturing the cursor**. Instead, these actions have to occur as a response to
  99. a JavaScript input event. In Godot, this means entering full screen from within
  100. a pressed input event callback such as ``_input`` or ``_unhandled_input``.
  101. Querying the :ref:`class_Input` singleton is not sufficient, the relevant
  102. input event must currently be active.
  103. For the same reason, the full screen project setting doesn't work unless the
  104. engine is started from within a valid input event handler. This requires
  105. :ref:`customization of the HTML page <doc_customizing_html5_shell>`.
  106. Audio
  107. ~~~~~
  108. Chrome restricts how websites may play audio. It may be necessary for the
  109. player to click or tap or press a key to enable audio.
  110. .. seealso:: Google offers additional information about their `Web Audio autoplay
  111. policies <https://sites.google.com/a/chromium.org/dev/audio-video/autoplay>`__.
  112. .. warning:: Access to microphone requires a
  113. :ref:`secure context <doc_javascript_secure_contexts>`.
  114. Networking
  115. ~~~~~~~~~~
  116. Low level networking is not implemented due to lacking support in browsers.
  117. Currently, only :ref:`HTTP client <doc_http_client_class>`,
  118. :ref:`HTTP requests <doc_http_request_class>`,
  119. :ref:`WebSocket (client) <doc_websocket>` and :ref:`WebRTC <doc_webrtc>` are
  120. supported.
  121. The HTTP classes also have several restrictions on the HTML5 platform:
  122. - Accessing or changing the ``StreamPeer`` is not possible
  123. - Threaded/Blocking mode is not available
  124. - Cannot progress more than once per frame, so polling in a loop will freeze
  125. - No chunked responses
  126. - Host verification cannot be disabled
  127. - Subject to `same-origin policy <https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy>`__
  128. Clipboard
  129. ~~~~~~~~~
  130. Clipboard synchronization between engine and the operating system requires a
  131. browser supporting the `Clipboard API <https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API>`__,
  132. additionally, due to the API asynchronous nature might not be reliable when
  133. accessed from GDScript.
  134. .. warning:: Requires a :ref:`secure context <doc_javascript_secure_contexts>`.
  135. Gamepads
  136. ~~~~~~~~
  137. Gamepads will not be detected until one of their button is pressed. Gamepads
  138. might have the wrong mapping depending on the browser/OS/gamepad combination,
  139. sadly the `Gamepad API <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API>`__
  140. does not provide a reliable way to detect the gamepad information necessary
  141. to remap them based on model/vendor/OS due to privacy considerations.
  142. .. warning:: Requires a :ref:`secure context <doc_javascript_secure_contexts>`.
  143. Boot splash is not displayed
  144. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  145. The default HTML page does not display the boot splash while loading. However,
  146. the image is exported as a PNG file, so :ref:`custom HTML pages <doc_customizing_html5_shell>`
  147. can display it.
  148. Serving the files
  149. -----------------
  150. Exporting for the web generates several files to be served from a web server,
  151. including a default HTML page for presentation. A custom HTML file can be
  152. used, see :ref:`doc_customizing_html5_shell`.
  153. The generated ``.html`` file can be used as ``DirectoryIndex`` in Apache
  154. servers and can be renamed to e.g. ``index.html`` at any time, its name is
  155. never depended on by default.
  156. The HTML page draws the game at maximum size within the browser window.
  157. This way it can be inserted into an ``<iframe>`` with the game's size, as is
  158. common on most web game hosting sites.
  159. The other exported files are served as they are, next to the ``.html`` file,
  160. names unchanged. The ``.wasm`` file is a binary WebAssembly module implementing
  161. the engine. The ``.pck`` file is the Godot main pack containing your game. The
  162. ``.js`` file contains start-up code and is used by the ``.html`` file to access
  163. the engine. The ``.png`` file contains the boot splash image. It is not used in
  164. the default HTML page, but is included for
  165. :ref:`custom HTML pages <doc_customizing_html5_shell>`.
  166. The ``.pck`` file is binary, usually delivered with the MIME-type
  167. :mimetype:`application/octet-stream`. The ``.wasm`` file is delivered as
  168. :mimetype:`application/wasm`.
  169. .. caution:: Delivering the WebAssembly module (``.wasm``) with a MIME-type
  170. other than :mimetype:`application/wasm` can prevent some start-up
  171. optimizations.
  172. Delivering the files with server-side compression is recommended especially for
  173. the ``.pck`` and ``.wasm`` files, which are usually large in size.
  174. The WebAssembly module compresses particularly well, down to around a quarter
  175. of its original size with gzip compression.
  176. **Hosts that provide on-the-fly compression:** GitHub Pages (gzip)
  177. **Hosts that don't provide on-the-fly compression:** itch.io, GitLab Pages
  178. (`supports manual gzip precompression <https://webd97.de/post/gitlab-pages-compression/>`__)
  179. .. tip::
  180. The Godot repository includes a
  181. `Python script to host a local web server <https://raw.githubusercontent.com/godotengine/godot/master/platform/web/serve.py>`__.
  182. This script is intended for testing the web editor, but it can also be used to test exported projects.
  183. Save the linked script to a file called ``serve.py``, move this file to the
  184. folder containing the exported project's ``index.html``, then run the
  185. following command in a command prompt within the same folder:
  186. ::
  187. # You may need to replace `python` with `python3` on some platforms.
  188. python serve.py --root .
  189. On Windows, you can open a command prompt in the current folder by holding
  190. :kbd:`Shift` and right-clicking on empty space in Windows Explorer, then
  191. choosing **Open PowerShell window here**.
  192. This will serve the contents of the current folder and open the default web
  193. browser automatically.
  194. Note that for production use cases, this Python-based web server should not
  195. be used. Instead, you should use an established web server such as Apache or
  196. nginx.
  197. .. _doc_javascript_eval:
  198. Calling JavaScript from script
  199. ------------------------------
  200. In web builds, the ``JavaScriptBridge`` singleton is implemented. It offers a single
  201. method called ``eval`` that works similarly to the JavaScript function of the
  202. same name. It takes a string as an argument and executes it as JavaScript code.
  203. This allows interacting with the browser in ways not possible with script
  204. languages integrated into Godot.
  205. .. tabs::
  206. .. code-tab:: gdscript
  207. func my_func():
  208. JavaScriptBridge.eval("alert('Calling JavaScript per GDScript!');")
  209. .. code-tab:: csharp
  210. private void MyFunc()
  211. {
  212. JavaScriptBridge.Eval("alert('Calling JavaScript per C#!');")
  213. }
  214. The value of the last JavaScript statement is converted to a GDScript value and
  215. returned by ``eval()`` under certain circumstances:
  216. * JavaScript ``number`` is returned as :ref:`class_float`
  217. * JavaScript ``boolean`` is returned as :ref:`class_bool`
  218. * JavaScript ``string`` is returned as :ref:`class_String`
  219. * JavaScript ``ArrayBuffer``, ``TypedArray`` and ``DataView`` are returned as :ref:`PackedByteArray<class_PackedByteArray>`
  220. .. tabs::
  221. .. code-tab:: gdscript
  222. func my_func2():
  223. var js_return = JavaScriptBridge.eval("var myNumber = 1; myNumber + 2;")
  224. print(js_return) # prints '3.0'
  225. .. code-tab:: csharp
  226. private void MyFunc2()
  227. {
  228. var jsReturn = JavaScriptBridge.Eval("var myNumber = 1; myNumber + 2;");
  229. GD.Print(jsReturn); // prints '3.0'
  230. }
  231. Any other JavaScript value is returned as ``null``.
  232. HTML5 export templates may be :ref:`built <doc_compiling_for_web>` without
  233. support for the singleton to improve security. With such templates, and on
  234. platforms other than HTML5, calling ``JavaScriptBridge.eval`` will also return
  235. ``null``. The availability of the singleton can be checked with the
  236. ``web`` :ref:`feature tag <doc_feature_tags>`:
  237. .. tabs::
  238. .. code-tab:: gdscript
  239. func my_func3():
  240. if OS.has_feature('web'):
  241. JavaScriptBridge.eval("""
  242. console.log('The JavaScriptBridge singleton is available')
  243. """)
  244. else:
  245. print("The JavaScriptBridge singleton is NOT available")
  246. .. code-tab:: csharp
  247. private void MyFunc3()
  248. {
  249. if (OS.HasFeature("web"))
  250. {
  251. JavaScriptBridge.Eval("console.log('The JavaScriptBridge singleton is available')");
  252. }
  253. else
  254. {
  255. GD.Print("The JavaScriptBridge singleton is NOT available");
  256. }
  257. }
  258. .. tip:: GDScript's multi-line strings, surrounded by 3 quotes ``"""`` as in
  259. ``my_func3()`` above, are useful to keep JavaScript code readable.
  260. The ``eval`` method also accepts a second, optional Boolean argument, which
  261. specifies whether to execute the code in the global execution context,
  262. defaulting to ``false`` to prevent polluting the global namespace:
  263. .. tabs::
  264. .. code-tab:: gdscript
  265. func my_func4():
  266. # execute in global execution context,
  267. # thus adding a new JavaScript global variable `SomeGlobal`
  268. JavaScriptBridge.eval("var SomeGlobal = {};", true)
  269. .. code-tab:: csharp
  270. private void MyFunc4()
  271. {
  272. // execute in global execution context,
  273. // thus adding a new JavaScript global variable `SomeGlobal`
  274. JavaScriptBridge.Eval("var SomeGlobal = {};", true);
  275. }