NUI interfaces (HTML/CSS/JS) · Lesson 2/3 · 9 min
Showing and hiding the interface (focus)
SetNuiFocus is the key: it gives the mouse to the web page. If you forget to remove it, you trap the player.
For the player to be able to click your menu, you have to give «focus» to the NUI with SetNuiFocus. And you must ALWAYS remove it when closing, or they're left with the mouse out and unable to play.
Lua: open and close
local abierto = false
RegisterCommand('menu', function()
abierto = true
SetNuiFocus(true, true) -- focus + mouse to the NUI
SendNUIMessage({ action = 'open' }) -- notify the JS
end)
-- Close (called by the JS via a callback, see next lesson)
RegisterNUICallback('close', function(_, cb)
abierto = false
SetNuiFocus(false, false) -- give control back to the game!
cb('ok')
end)client.lua
window.addEventListener('message', (e) => {
if (e.data.action === 'open') {
document.getElementById('app').style.display = 'block';
}
});
// Close with ESC
document.onkeyup = (e) => {
if (e.key === 'Escape') {
document.getElementById('app').style.display = 'none';
fetch(`https://${GetParentResourceName()}/close`, { method: 'POST', body: '{}' });
}
};app.js
Forgetting SetNuiFocus(false, false) when closing is THE most common NUI bug: the player is left with the cursor and can't move. Always wire up closing with ESC and via callback.
Practice what you learned
0/3Al cerrar un menú NUI, ¿por qué es imprescindible llamar a SetNuiFocus(false, false)?
Pista
El foco es el ratón. ¿Quién debe tenerlo cuando el menú está cerrado?
Este callback cierra el menú pero deja al jugador atrapado con el ratón. Arréglalo.
Este código tiene un fallo:
RegisterNUICallback('close', function(_, cb) abierto = false cb('ok')end)Reescríbelo corregido:
Pista
Falta devolver el foco al juego al cerrar.
Completa el comando que abre el menú: da foco y ratón a la NUI y avísala con un mensaje.
RegisterCommand('menu', function() SetNuiFocus(, ) SendNUIMessage({ action = })end)Pista
Para abrir: foco y ratón en true; el action (entre comillas) que escucha el JS es 'open'.
Challenge: code it yourself
Add that pressing a 'Close' button in the HTML hides the menu and gives control back to the game.
Write it yourself in your editor (VS Code) and test it on your server. You learn here by doing it, not by copying.
See hint
onclick → fetch(...'/close') → RegisterNUICallback('close') with SetNuiFocus(false,false).
Escribe aquí tu solución:
