Custom apps

Getting started with a custom app

A minimal working custom app in three files, with registration, theme, insets, a NUI callback, a notification and a contact picker.

#What this builds

A resource called my-app with three files. The app:

  • registers itself into the phone and is installed on every phone,
  • reads the theme and the safe-area insets,
  • calls a NUI callback in its own resource,
  • sends a notification,
  • opens the contact picker.

Field and message details are in Custom apps overview and App API.

#fxmanifest.lua

Every file the page loads must be listed under files.

luafx_version 'cerulean'
game 'gta5'
lua54 'yes'

client_script 'client.lua'
files { 'html/index.html', 'html/icon.png' }

#client.lua

The app is registered when the resource starts and again each time the phone loads, so it survives an FX Phone restart.

lualocal RESOURCE = GetCurrentResourceName()

local function register()
    exports['fx-phone']:AddCustomApp({
        identifier = 'hello',
        name = 'Hello',
        description = 'A minimal fx-phone app.',
        defaultApp = true,
        ui = RESOURCE .. '/html/index.html',
        icon = RESOURCE .. '/html/icon.png',
    })
end

AddEventHandler('fx-phone:client:phoneLoaded', register)
CreateThread(function()
    if GetResourceState('fx-phone') == 'started' then register() end
end)

RegisterNUICallback('whoami', function(_, cb)
    cb({ number = exports['fx-phone']:GetPhoneNumber(), hour = GetClockHours() })
end)

#html/index.html

html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
  :root { --bg: #f2f2f7; --card: #fff; --text: #000; --tint: #007aff; }
  [data-theme='dark'] { --bg: #000; --card: #1c1c1e; --text: #fff; --tint: #0a84ff; }
  html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 17px/22px system-ui, sans-serif; }
  body { box-sizing: border-box; padding: calc(var(--top) + 12px) 16px calc(var(--bottom) + 12px); }
  button, input { display: block; width: 100%; box-sizing: border-box; margin-top: 10px; padding: 12px;
    border: 0; border-radius: 12px; background: var(--card); color: var(--tint); font: inherit; text-align: left; }
  input { color: var(--text); }
</style>
</head>
<body>
  <h1>Hello</h1>
  <input id="name" placeholder="Your name">
  <button id="whoami">Ask my resource</button>
  <button id="notify">Send a notification</button>
  <button id="contact">Pick a contact</button>
  <p id="out"></p>
<script>
  const query = new URLSearchParams(location.search);
  const appId = query.get('app');
  const resource = query.get('resource');
  const root = document.documentElement;
  const $ = (id) => document.getElementById(id);
  const show = (text) => { $('out').textContent = text; };
  const send = (action, data) => parent.postMessage({ type: 'fx-phone', appId, action, data }, '*');

  const theme = (value) => { root.dataset.theme = value === 'light' ? 'light' : 'dark'; };
  const insets = ({ top, bottom }) => {
    root.style.setProperty('--top', `${top}px`);
    root.style.setProperty('--bottom', `${bottom}px`);
  };
  theme(query.get('theme'));
  insets({ top: Number(query.get('insetTop')) || 59, bottom: Number(query.get('insetBottom')) || 34 });

  window.addEventListener('message', ({ data: msg }) => {
    if (!msg || typeof msg !== 'object' || msg.type !== 'fx-phone') return;
    if (msg.action === 'ready') { theme(msg.theme); insets(msg.insets); }
    if (msg.action === 'theme') theme(msg.theme);
    if (msg.action === 'pickResult' && msg.id === 'contact') {
      show(msg.data ? `${msg.data.firstname} ${msg.data.lastname ?? ''}: ${msg.data.number}` : 'Cancelled');
    }
  });

  $('whoami').onclick = async () => {
    const res = await fetch(`https://${resource}/whoami`, { method: 'POST', body: '{}' });
    const data = await res.json();
    show(`Number ${data.number}, game hour ${data.hour}`);
  };
  $('notify').onclick = () => send('notification', { title: 'Hello', description: `Hi ${$('name').value || 'there'}` });
  $('contact').onclick = () => send('pick', { id: 'contact', type: 'contact' });
  $('name').addEventListener('focus', () => send('setFocus', { focused: true }));
  $('name').addEventListener('blur', () => send('setFocus', { focused: false }));
</script>
</body>
</html>

#Start it

Add the resource after the phone in server.cfg:

cfgensure fx-phone
ensure my-app

The app is installed on every phone because of defaultApp = true. Without it, players install the app from the App Store.

#What each part does

  1. Query string. The phone loads the page with app, resource, theme, insetTop and insetBottom in the query string. The page uses them for its first paint, before any message arrives.
  2. ready and theme messages. After the page loads, the phone posts ready with the theme and insets. A later theme change is posted as theme. The page is not reloaded.
  3. Own NUI callback. The iframe is your page on https://cfx-nui-<resource>/, so fetch('https://<resource>/whoami') reaches the RegisterNUICallback handler in client.lua like any NUI page.
  4. Messages to the phone. send('notification', ...) and send('pick', ...) post to the parent window. The picker answer comes back as pickResult with the same id.
  5. Text input. setFocus with focused: true on focus and false on blur keeps typing from moving the character. Always send both.

#Next steps

  • Push data from Lua to the page with SendCustomAppMessage. See App API.
  • Put a count on the icon with SetAppBadge, show a confirmation with DoPhoneConfirmation, or keep per-character data with SetAppData. See More phone features.
  • Read Performance before adding timers or polling.