Custom apps

App API

The iframe a custom app runs in, its lifecycle, every message between the page and the phone, pickers, dialogs, focus and the Lua features an app can use.

#The iframe

The page is loaded with these query parameters:

Parameter Example Meaning
phone fx-phone Always fx-phone
app garage Your app id
resource my-garage The resource that registered the app
theme dark light or dark, already resolved (never auto)
insetTop 59 Pixels covered by the status bar and the Dynamic Island
insetBottom 34 Pixels covered by the home indicator
scale 1 The player's phone size

The parameters are added to the page's own query string and replace any of the same name in ui. A ui with its own ?tab=garage keeps it.

Facts about the frame:

  • It fills the whole screen of the phone. Keep tappable content between insetTop and insetBottom.
  • The final ui address must be https://. Resource pages are, as https://cfx-nui-<resource>/. Anything else opens as a blank page.
  • It is sandboxed with scripts, same-origin, forms, modals, popups and downloads allowed. Autoplay and clipboard write are allowed.
  • The phone only posts messages to your page's origin, and only takes messages from your own iframe.

#Lifecycle

  1. The player opens the app. The iframe is created and the page loads.
  2. The phone posts, in this order: ready, the string componentsLoaded, visibility, landscape, stage, and open when the app was opened with data.
  3. While the app is in the app switcher the iframe stays loaded, so the page keeps its state when the player goes home and comes back. visibility reports false while it is not in front.
  4. If the player opens many apps, the oldest leave the switcher. Their pages are unloaded and load fresh next time.
  5. An app registered with keepOpen = true is not unloaded. It stays loaded until the app is removed, and is told through visibility when it is hidden.
  6. When the registering resource stops, or RemoveCustomApp is called, the app is removed from the phone.

On the Lua side, fx-phone:customApp:opened and fx-phone:customApp:closed fire with the app id when the app comes to the front or leaves it.

#Messages to the app

Listen with window.addEventListener('message', ...). Messages from the phone carry type: 'fx-phone'.

Message When
{ type: 'fx-phone', action: 'ready', theme, insets: { top, bottom } } First, right after the page loaded
'componentsLoaded' (a plain string) Right after ready, in lb-phone's order
{ type: 'fx-phone', action: 'visibility', visible } After ready, and whenever it changes. visible is true only while your app is in front and the phone is open and unlocked
{ type: 'fx-phone', action: 'landscape', landscape } After ready, and whenever the phone turns on its side or stands up while your app is in front
{ type: 'fx-phone', action: 'stage', stage, scale } After ready, and whenever it changes. stage is true while the phone is in the middle of the screen for your app. scale is how much larger than its layout size the phone is drawn
{ type: 'fx-phone', action: 'open', data } After ready, and on every later OpenApp(appId, data) with non-empty data
{ type: 'fx-phone', action: 'theme', theme } The theme changed. The page is not reloaded
{ type: 'fx-phone', action: 'key', state, code, repeat } A claimed key was pressed while the phone's page, not yours, had the keyboard. state is down or up
{ type: 'fx-phone', action: 'pickResult', id, data } Answer to a pick request. data is null when cancelled
{ type: 'fx-phone', action: 'contextMenu:result', data: { id, button } } Answer to contextMenu. button is the chosen button id, null when dismissed
{ type: 'fx-phone', action: 'popUp:result', data: { id, button } } Answer to popUp. button is the chosen button id, null when dismissed
Whatever Lua sent with SendCustomAppMessage(appId, data) Posted as it is, without type

Pushing data from Lua:

luaexports['fx-phone']:SendCustomAppMessage('garage', { action = 'vehicles', list = vehicles })
jswindow.addEventListener('message', ({ data }) => {
  if (data?.action === 'vehicles') render(data.list);
});

SendCustomAppMessage returns false, 'not_found' when no app with that id is registered. It is also available as SendCustomNUIMessage.

#Messages from the app

Post to the phone with:

jsparent.postMessage({ type: 'fx-phone', appId, action, data }, '*');

type: 'cylex_phone' is accepted too.

Action Data What happens
notification { title?, description?, icon? } A banner from your app. title defaults to the app name. icon (or thumbnail) is an image URL. Display only, no sound
close Closes the app if it is on screen
openApp { app } Opens another app by id, if the player is allowed to see it
setFocus { focused } true while one of your text fields has focus, so typing does not move the character. false on blur
setLandscape { on } true turns the phone on its side while your app is in front. false stands it up again. The phone answers with a landscape message
setStage { on } true moves the phone to the middle of the game screen at the largest size that fits. false puts it back. The phone answers with a stage message
claimKeys { alt } alt: true claims left Alt while your app is in front. Alt no longer looks around, and when the phone's own page has the keyboard the press reaches you as a key message
pick { id, type, opts? } Opens a picker. The answer comes back as pickResult with the same id
contextMenu { id, title?, items } An action sheet with a cancel row. Answered with contextMenu:result
popUp { id, title, description, buttons } An alert. Answered with popUp:result
nuiCallback { action, data } Fires the client event <resource>:phoneApp:event with appId, action, data in your resource

Unknown actions are ignored.

#Notifications from the page

jssend('notification', { title: 'Garage', description: 'Your car is ready', icon: 'https://cfx-nui-my-garage/html/car.png' });
  • The banner is shown under your app id, so the player's per-app notification switch applies.
  • It is display only. It makes no sound and is not stored for offline players.
  • An image on a host the server does not allow is dropped and the banner shows without it. Files from a resource and data:image/ values always pass.

For a notification with sound, or one that is stored for an offline player, send it from Lua. See Client exports: Notifications and Server exports: Notifications.

#Pickers

jssend('pick', { id: 'shots', type: 'gallery', opts: { multiple: true, max: 3 } });
send('pick', { id: 'selfie', type: 'camera', opts: { kind: 'photo' } });

Types: contact, gallery, camera, gif, emoji, color.

Option For Meaning
title all Sheet title
multiple, max contact, gallery Pick several, up to max. data is then a list
kind gallery, camera photo or video

Results are the same as for the ShowComponent export: a contact is { id, number, firstname, lastname, avatar, ... }, a gallery item is { id, url, thumbnail, kind, ... }. See Client exports: Dialogs.

camera opens the Camera app with a Use / Retake review, answers with the saved item, then returns to your app.

#Context menus and popups

Buttons in contextMenu.items and popUp.buttons are { id?, title, style? }. label is read as well as title. id defaults to the position as a string ('1', '2', ...). style: 'destructive', or lb-phone's color: 'red', draws the button red.

jssend('contextMenu', {
  id: 'row-7',
  title: 'Vehicle',
  items: [{ id: 'track', title: 'Track' }, { id: 'sell', title: 'Sell', style: 'destructive' }],
});

window.addEventListener('message', ({ data: msg }) => {
  if (msg?.type === 'fx-phone' && msg.action === 'contextMenu:result' && msg.data.button === 'sell') confirmSale();
});

#Landscape

An app registered with landscape = true turns sideways when the player rotates the phone in Control Centre or a script calls SetLandscape(true). An app without it can still ask for landscape itself with the setLandscape message, for example when a video goes full screen.

While the phone lies on its side your page is laid out 852 by 393 and receives landscape: true. It receives landscape: false when the phone stands up again: the player swiped up from the bottom edge, opened Control Centre or left the app. The first swipe up in landscape only stands the phone up, so leave your full-screen view when you receive landscape: false.

#Stage

setStage with on: true moves the phone to the middle of the game screen at the largest size that fits. It is meant for games. It ends by itself when your app leaves the front, the phone locks or is put away.

The phone answers with a stage message. Multiply a canvas's pixel ratio by its scale to stay sharp.

#Calling your resource

The iframe is your page on https://cfx-nui-<resource>/, so it can call your resource's RegisterNUICallback handlers directly, like a normal NUI page:

jsconst res = await fetch(`https://${resource}/getVehicles`, { method: 'POST', body: '{}' });

nuiCallback is the alternative for apps written for lb-phone's fallback path. It arrives as a client event:

luaAddEventHandler(GetCurrentResourceName() .. ':phoneApp:event', function(appId, action, data)
    if action == 'refresh' then
        -- ...
    end
end)

The relay answers not_found when the app has no owning resource (a Config.CustomApps entry without resource) and invalid when action is not a string.

Anything the page sends to your resource comes from the player's client. Check it on the server before acting on it.

#Focus

The phone owns NUI focus. With Config.WalkWhileOpen = true the game keeps the movement keys while the phone is open. Post setFocus with focused: true while a text field has focus and focused: false on blur. From Lua, SetInputFocus(focused) and ToggleFocusKeepInput(keepInput) do the same.

Never call SetNuiFocus yourself while your app is open.

#Opening the app with data

luaexports['fx-phone']:OpenApp('garage', { plate = 'ABC123' })

The data reaches the page as an open message after ready, so a deep link works even when the page was not loaded yet. Each OpenApp call with non-empty data is delivered once.

#More phone features

All of these are client exports unless noted.

Feature Export Reference
A count on your icon; 0 clears it SetAppBadge(id, count) Custom apps
Notification from Lua under your app id SendNotification({ app = 'garage', title = ..., content = ... }) Notifications
Confirmation sheet returning true or false DoPhoneConfirmation(title, text, icon) Dialogs
Pickers from Lua ShowComponent({ type = 'gallery' }) Dialogs
Popups and context menus calling Lua functions SetPopUp, SetContextMenu Dialogs
Now Playing on the lock screen and Dynamic Island ShowMusicTray, UpdateMusicTray, RemoveMusicTray Dynamic Island
Live activity with progress, lines and buttons ShowLiveTray, UpdateLiveTray, RemoveLiveTray Dynamic Island
Photo URL back to your Lua code OpenCamera({ mode = 'photo' }, cb) Camera
A rebindable key that runs only while your bind is active AddKeyBind Other
Per-character key-value storage (server) SetAppData, GetAppDataFor App data

Storage example. Values are any JSON up to 16 KB per key. Validate what a client sends before you store it.

lua-- server.lua
RegisterNetEvent('my-app:save', function(value)
    local src = source
    local user = exports['fx-phone']:GetUserDataBySource(src)
    if not user or type(value) ~= 'string' or #value > 200 then return end
    exports['fx-phone']:SetAppData(user.identifier, 'hello', 'note', value)
end)

#Dynamic Island trays

Two kinds of tray are available to an app:

  • Music tray. Now Playing on the island and the lock screen: cover, title, artist, play state and controls. The buttons call the handlers you pass (play, pause, next, prev, seek). The island has no scrubber, so seek is not called yet.
  • Live activity. An icon, a title and subtitle, a progress from 0 to 1, up to 3 buttons, and an expanded view (4 lines, 3 buttons) shown when the player opens the island.

Rules for both:

  • A tray belongs to the resource that created it. Only that resource can update or remove it, and it goes when that resource stops.
  • Reuse your own id. Showing the same id again replaces the tray instead of stacking a second one.
  • A tray stays up while the phone is put away and is there again when it opens. The phone re-sends it after its UI reloads. Only an FX Phone restart clears it, so show it again on fx-phone:client:phoneLoaded.
  • The island shows one activity at a time, by priority: incoming call, call, alarm, timer, music, live activity.

Music tray:

lualocal TRAY = 'myradio'

local function showTrack(t)
    exports['fx-phone']:ShowMusicTray({
        id = TRAY,
        title = t.title, artist = t.artist, cover = t.cover,
        playing = true, duration = t.length, position = 0,
        handlers = {
            play  = function() MyPlayer.Resume() end,
            pause = function() MyPlayer.Pause() end,
            next  = function() MyPlayer.Next() end,
            prev  = function() MyPlayer.Previous() end,
        },
    })
end

AddEventHandler('myradio:paused',  function() exports['fx-phone']:UpdateMusicTray(TRAY, 'playing', false) end)
AddEventHandler('myradio:stopped', function() exports['fx-phone']:RemoveMusicTray(TRAY) end)

Live activity:

lualocal delivery = exports['fx-phone']:ShowLiveTray({
    id = 'delivery',
    title = 'Delivery', subtitle = '2.4 km',
    icon = 'truck', color = '#30D158', progress = 0,
    buttons = {
        { id = 'gps', icon = 'navigation-arrow', label = 'GPS', onPress = function() SetNewWaypoint(dest.x, dest.y) end },
    },
    expanded = {
        lines = { 'Order #12', 'Tip: $40' },
        buttons = { { id = 'cancel', icon = 'x', label = 'Cancel', onPress = function() TriggerServerEvent('mydelivery:cancel') end } },
    },
})

exports['fx-phone']:UpdateLiveTray(delivery, { progress = 0.5, subtitle = '1.2 km to go' })
exports['fx-phone']:RemoveLiveTray(delivery)

Signatures and return values are in Client exports: Dynamic Island.

#lb-phone page helpers

lb-phone apps include https://cfx-nui-lb-phone/ui/components.js in their HTML and call the globals it defines (fetchNui, setContextMenu, setPopUp, useCamera, selectGallery, getSettings, onSettingsChange, sendNotification and others). FX Phone's version of that script is html/compat/lb-components.js. The lb-phone shim resource serves it as ui/components.js, so those pages run unchanged and their calls go through the message protocol on this page.

A new app written for FX Phone does not need it. See LB Phone compatibility.