Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

Exportar para la Web

Ver también

Esta página describe cómo exportar un proyecto de Godot a HTML5. Si estás buscando compilar binarios del editor o plantillas de exportación desde la fuente en su lugar, lee Compilando para la Web.

HTML5 export allows publishing games made in Godot Engine to the browser. This requires support for WebAssembly, WebGL and SharedArrayBuffer in the user's browser.

Atención

Projects written in C# using Godot 4 currently cannot be exported to the web. To use C# on web platforms, use Godot 3 instead.

Truco

Use the browser-integrated developer console, usually opened with F12 (Cmd + Option + I on macOS), to view debug information like JavaScript, engine, and WebGL errors.

Atención

Godot 4's HTML5 exports currently cannot run on macOS and iOS due to upstream bugs with SharedArrayBuffer and WebGL 2.0. We recommend using macOS and iOS native export functionality instead, as it will also result in better performance.

Godot 3's HTML5 exports are more compatible with various browsers in general, especially when using the GLES2 rendering backend (which only requires WebGL 1.0).

Versión de WebGL

Godot 4.0 and later can only target WebGL 2.0 (using the Compatibility rendering method). There is no stable way to run Vulkan applications on the web yet.

See Can I use WebGL 2.0 for a list of browser versions supporting WebGL 2.0. Note that Safari has several issues with WebGL 2.0 support that other browsers don't have, so we recommend using a Chromium-based browser or Firefox if possible.

Opciones de exportación

Si hay disponible una plantilla de exportación web ejecutable, aparece un botón entre los botones Detener escena y Reproducir escena en el editor para abrir rápidamente el juego en el navegador predeterminado para realizar pruebas.

If you plan to use VRAM compression make sure that Vram Texture Compression is enabled for the targeted platforms (enabling both For Desktop and For Mobile will result in a bigger, but more compatible export).

Si se da una ruta a un archivo HTML shell personalizado, se utilizará en lugar de la página HTML predeterminada. Ver Página HTML personalizada para la exportación web.

Head Include se agrega al elemento <head> de la página HTML generada. Esto permite, por ejemplo, cargar fuentes web y APIs JavaScript de terceros, incluir CSS o ejecutar código JavaScript.

Importante

Cada proyecto debe generar su propio archivo HTML. Al exportar, varios placeholders se reemplazan en el archivo HTML generado específicamente para las opciones de exportación correspondientes. Cualquier modificación al archivo HTML generado serán perdidas en exportaciones futuras. Para personalizar el archivo generado, utiliza la opción Carcasa HTML personalizada.

Limitaciones

Por razones de seguridad y privacidad, muchas de las funciones que funcionan sin esfuerzo en plataformas nativas son más complicadas en la plataforma web. A continuación hay una lista de limitaciones que debes tener en cuenta a la hora de portar un juego Godot a la web.

Importante

Los proveedores de navegadores están haciendo más y más funcionalidades solo disponibles en contextos seguros <https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts> _, esto significa que tales características solo están disponibles si la página web se sirve a través de una conexión HTTPS segura (localhost generalmente está exento de tal requisito).

Uso de cookies para la persistencia de datos

Los usuarios deben permitir cookies (específicamente IndexedDB) si se desea la persistencia del sistema de archivos user://. Cuando se juega a un juego presentado en un iframe, también deben estar habilitadas las cookies de terceros. El modo de navegación de incógnito/privado también evita la persistencia.

El método OS.is_userfs_persistent() puede usarse para comprobar si el sistema de ficheros user:// es persistente, pero puede dar falsos positivos en algunos casos.

Procesamiento en segundo plano

El proyecto se pausará por el navegador cuando la pestaña ya no sea la pestaña activa en el navegador del usuario. Esto significa que funciones como _process() y _physics_process() ya no se ejecutarán hasta que la pestaña vuelva a ser activa por el usuario (al cambiar de nuevo a la pestaña). Esto puede causar que los juegos en red se desconecten si el usuario cambia de pestaña durante un largo período de tiempo.

Esta limitación no se aplica a las ventanas del navegador que no tienen el enfoque. Por lo tanto, desde el lado del usuario, se puede resolver ejecutando el proyecto en una ventana separada en lugar de una pestaña separada.

Captura de pantalla completa y ratón

Los navegadores no permiten ingresar a pantalla completa arbitrariamente. Lo mismo ocurre con capturar el cursor. En su lugar, estas acciones tienen que ocurrir como respuesta a un evento de entrada de JavaScript. En Godot, implica que se debe cambiar pantalla completa desde una llamada de entrada como _input o _unhandled_input. Consultando el singleton Input no será suficiente, el evento correspondiente debe estar actualmente activo.

Por la misma razón, la opción de proyecto a pantalla completa no funciona a menos que el motor sea lanzado desde un manejador de eventos de entrada válido. Esto requiere customizar la página HTML.

Audio

Some browsers restrict autoplay for audio on websites. The easiest way around this limitation is to request the player to click, tap or press a key/button to enable audio, for instance when displaying a splash screen at the start of your game.

Ver también

Google ofrece información adicional acerca de su política de reproducción automática de Web Audio.

Apple's Safari team also posted additional information about their Auto-Play Policy Changes for macOS.

Advertencia

El acceso al micrófono requiere secure context.

Redes

Las redes de bajo nivel no se implementan debido a la falta de soporte en los navegadores.

Actualmente, solo están soportados: HTTP client <doc_http_client_class>, HTTP requests, WebSocket (client) y WebRTC.

Las clases HTTP también tienen varias restricciones en la plataforma HTML5:

  • No es posible acceder o cambiar el StreamPeer

  • El modo de hilos/bloqueo no está disponible

  • No se puede progresar más de una vez por fotograma, por lo que el sondeo en un bucle se congelará

  • No hay respuestas fragmentadas

  • La verificación del host no se puede deshabilitar

  • Sujeto a la política de mismo origen

Portapapeles

La sincronización del portapapeles entre el motor (Godot) y el sistema operativo requiere de un navegador que soporte la Clipboard API, además, debido a la naturaleza de la API asíncrona, el portapapeles, podría no ser de confianza cuando se accede desde GDScript.

Advertencia

Requiere un: ref: secure context <doc_javascript_secure_contexts>.

Mandos de juego

Los Mandos no se detectarán hasta que se presione uno de sus botones. Los Mandos pueden tener un mapeo incorrecto dependiendo de la combinación de navegador / sistema operativo / mando, lamentablemente la API de Gamepad <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API> `__ no proporcionan una forma fiable de detectar la información del mando necesaria para reasignarlos según el modelo / proveedor / sistema operativo debido a consideraciones de privacidad.

Advertencia

Requiere un: ref: secure context <doc_javascript_secure_contexts>.

La pantalla de inicio no es mostrada

La página HTML por defecto no muestra la pantalla de inicio mientras se carga. Sin embargo, la imagen es exportada como un archivo PNG, así las páginas HTML customizadas pueden mostrarla.

Entrega de archivos

Exportar para la web genera varios archivos para ser servidos desde un servidor web, incluyendo una página HTML por defecto para la presentación. Se puede utilizar un archivo HTML personalizado, visita Página HTML personalizada para la exportación web.

Advertencia

To ensure low audio latency and the ability to use Thread in web exports, Godot 4 web exports always use SharedArrayBuffer. This requires a secure context, while also requiring the following CORS headers to be set when serving the files:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

If you don't control the web server or are unable to add response headers, use coi-serviceworker as a workaround.

If the client doesn't receive the required response headers, the project will not run.

The generated .html file can be used as DirectoryIndex in Apache servers and can be renamed to e.g. index.html at any time. Its name is never depended on by default.

The HTML page draws the game at maximum size within the browser window. This way, it can be inserted into an <iframe> with the game's size, as is common on most web game hosting sites.

Los otros archivos exportados se sirven tal cual, junto al archivo .html, sin cambios en los nombres. El archivo .wasm es un módulo binario de WebAssembly que implementa el motor. El archivo .pck es el paquete principal de Godot que contiene tu juego. El archivo .js contiene código de inicio y es usado por el archivo .html para acceder al motor. El archivo .png contiene la imagen de bienvenida al inicio. No se utiliza en la página HTML por defecto, pero se incluye para páginas HTML personalizadas.

El archivo .pck es binario, normalmente se entrega con el MIME-type application/octet-stream. El archivo .wasm se entrega como application/wasm.

Advertencia

Emitir el modulo WebAssembly (.wasm) con un tipo MIME diferente a application/wasm puede evitar algunas optimizaciones de arranque.

Delivering the files with server-side compression is recommended especially for the .pck and .wasm files, which are usually large in size. The WebAssembly module compresses particularly well, down to around a quarter of its original size with gzip compression. Consider using Brotli precompression if supported on your web server for further file size savings.

Host que proveen compresión sobre la marcha: GitHub Pages (gzip)

Host que no proveen compresión sobre la marcha: itch.io, GitLab Pages (soporta precompresión manual con gzip)

Truco

The Godot repository includes a Python script to host a local web server. This script is intended for testing the web editor, but it can also be used to test exported projects.

Save the linked script to a file called serve.py, move this file to the folder containing the exported project's index.html, then run the following command in a command prompt within the same folder:

# You may need to replace `python` with `python3` on some platforms.
python serve.py --root .

On Windows, you can open a command prompt in the current folder by holding Shift and right-clicking on empty space in Windows Explorer, then choosing Open PowerShell window here.

This will serve the contents of the current folder and open the default web browser automatically.

Note that for production use cases, this Python-based web server should not be used. Instead, you should use an established web server such as Apache or nginx.

Llamada a JavaScript desde script

In web builds, the JavaScriptBridge singleton is implemented. It offers a single method called eval that 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.

func my_func():
    JavaScriptBridge.eval("alert('Calling JavaScript per GDScript!');")

El valor de la última sentencia JavaScript es convertido a un valor GDScript y devuelto por eval() bajo ciertas circunstancias:

  • JavaScript number is returned as float

  • JavaScript boolean is returned as bool

  • JavaScript string is returned as String

  • JavaScript ArrayBuffer, TypedArray and DataView are returned as PackedByteArray

func my_func2():
    var js_return = JavaScriptBridge.eval("var myNumber = 1; myNumber + 2;")
    print(js_return) # prints '3.0'

Cualquier otro valor de JavaScript se devuelve como 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:

func my_func3():
    if OS.has_feature('web'):
        JavaScriptBridge.eval("""
            console.log('The JavaScriptBridge singleton is available')
        """)
    else:
        print("The JavaScriptBridge singleton is NOT available")

Truco

Los strings multilinea de GDScript, rodeados por 3 comillas dobles """ como arriba en my_func3(), son útiles para mantener el código JavaScript más legible.

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:

func my_func4():
    # execute in global execution context,
    # thus adding a new JavaScript global variable `SomeGlobal`
    JavaScriptBridge.eval("var SomeGlobal = {};", true)

Variables de entorno

You can use the following environment variables to set export options outside of the editor. During the export process, these override the values that you set in the export menu.

HTML5 export environment variables

Export option

Environment variable

Encryption / Encryption Key

GODOT_SCRIPT_ENCRYPTION_KEY