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

lua
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

javascript
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/3
Test

Al 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?

Corrige el error

Este callback cierra el menú pero deja al jugador atrapado con el ratón. Arréglalo.

Este código tiene un fallo:

1RegisterNUICallback('close', function(_, cb)
2 abierto = false
3 cb('ok')
4end)

Reescríbelo corregido:

Pista

Falta devolver el foco al juego al cerrar.

Rellena los huecos

Completa el comando que abre el menú: da foco y ratón a la NUI y avísala con un mensaje.

1RegisterCommand('menu', function()
2 SetNuiFocus(, )
3 SendNUIMessage({ action = })
4end)
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:

How was this lesson?