JavaScript API

On this page

ph-app.js adds window.phApp, with helpers for the things every app needs: URLs that work behind relative URLs, requests with timeouts and readable errors, formatting, CSV export, live data, toasts, dialogs, and the connection to Performance Hub. The optional scripts add their own functions to the same object.

Wait for DOMContentLoaded before calling phApp; the kit scripts load with defer.

document.addEventListener('DOMContentLoaded', async () => {
  const summary = await phApp.fetchJSON('api/summary');
  document.querySelector('#total').textContent = phApp.format.number(summary.total);
});

At a glance

MemberWhat it does
url(path), wsUrl(path), basePath()URLs that stay inside the app
fetchJSON(path, options)Requests JSON, with a timeout and readable errors
errorsThe error classes fetchJSON throws
formatNumbers, currency, percentages, dates, times, durations and bytes
csvCSV downloads
liveServer-sent events and WebSockets that reconnect
toast(message, options)Short messages in the corner
dialogOpens and closes dialogs; asks for confirmation
tabs.select(tab)Selects a tab from code
enhance(root)Wires up tabs, menus and tables added later (usually automatic)
theme(), setTheme(), onThemeChange()Light and dark mode
embedded(), host(), onHostReady(), ready(), navigate()The Performance Hub connection
versionThe kit version, such as '1.0.0'

Optional scripts add chart, kpi and heatmap (Charts), calendar (Calendar), editor, richText and sanitizeHtml (Rich text editor), map (Maps), dataGrid (Data grid) and sortable (Drag and drop).

URLs

An app doesn't always open at the root of its address. A URL starting with / points at the root of the whole site, so use relative URLs, or these helpers.

FunctionReturns
phApp.url(path)path under the app's base. phApp.url('/api/items') returns that path inside the app's own address instead of at the root of the site. Full URLs (https://…) are returned unchanged.
phApp.wsUrl(path)The same as a ws: or wss: URL, for WebSockets
phApp.basePath()The app's base path, ending in /

fetchJSON

try {
  const orders = await phApp.fetchJSON('api/orders', { query: { store: 'ormsby', days: 14 } });
  render(orders);
} catch (error) {
  showError(error.message); // "Could not reach the server. Check the connection and try again."
}

await phApp.fetchJSON('api/customers/42', { method: 'PATCH', body: { tier: 'Gold' } });

fetchJSON(path, options) resolves path with phApp.url(), sends cookies for the same origin, and returns the parsed JSON. A 204 or empty response returns null; a response that isn't JSON returns the text.

OptionDefaultWhat it does
bodynoneObjects are sent as JSON with Content-Type: application/json. Strings, FormData, Blob and URLSearchParams are sent as they are.
querynoneAdded to the URL. null and undefined values are left out.
timeout15000Milliseconds before giving up
signalnoneAn AbortSignal to cancel the request
method, headers, …Any other fetch option. Accept: application/json is added unless you set it.

Errors

Every error has a message you can show people.

ErrorWhenmessage
phApp.errors.PhHttpErrorThe server answered 4xx or 5xxThe server's message, error or detail field, a short text body, or the status text. Also has status and body.
phApp.errors.PhTimeoutErrorNo answer within timeout"The request took longer than 15s. Try again."
phApp.errors.PhNetworkErrorThe server couldn't be reached"Could not reach the server. Check the connection and try again."
catch (error) {
  if (error instanceof phApp.errors.PhHttpError && error.status === 404) showNotFound();
  else showError(error.message);
}

format

Formatters use the viewer's language (navigator.language), and return "—" for missing or invalid values. Examples are for en-AU.

FunctionExampleResult
number(value, options?)number(1234567.891)1,234,567.891
compact(value, digits = 1)compact(12300)12.3K
currency(value, currency = 'AUD', options?)currency(48210)$48,210.00
percent(ratio, digits = 0)percent(0.256), percent(0.9982, 2)26%, 99.82%
date(value, options?)date('2026-11-17')17 Nov 2026
dateTime(value, options?)dateTime(Date.now())17 Nov 2026, 9:30 am
time(value, options?)time(Date.now())9:30 am
relative(value, now?)three minutes ago, two days ahead3 minutes ago, in 2 days
duration(ms)duration(45000), duration(7509000)45s, 2h 5m
bytes(value, digits = 1)bytes(1536), bytes(512)1.5 KB, 512 B
setLocale(locale)setLocale('en-GB')Changes the language for every formatter

options are Intl.NumberFormat or Intl.DateTimeFormat options. Dates take a Date, a timestamp or an ISO string.

csv

phApp.csv.download(phApp.csv.filename('orders'), orders, [
  { header: 'Store', value: (order) => order.store },
  { header: 'Orders', value: (order) => order.count },
  { header: 'Date', value: (order) => order.date },
]);
FunctionWhat it does
csv.download(filename, rows, columns?)Downloads a CSV. With columns ({ header, value(row) }), one row per item; without, rows is an array of arrays. .csv is added if missing. Dates become ISO strings; true and false become Yes and No.
csv.filename(prefix)A timestamped name: orders__2026-11-17T09:30:00.000Z.csv

live

live.sse() and live.ws() open server-sent events or a WebSocket, and reconnect when the connection drops: after about 1 second, doubling up to 30 seconds, and straight away when the tab becomes visible again.

const feed = phApp.live.sse('api/events', {
  onMessage: (data) => addRow(data),             // JSON is parsed for you
  events: { order: (data) => addOrder(data) },  // named events
  onStatus: (status) => (badge.textContent = status),
});

const socket = phApp.live.ws('ws', { onMessage: (data) => update(data) });
socket.send({ subscribe: 'orders' });            // objects are sent as JSON; false while disconnected

feed.close();

Status is 'connecting', 'open', 'reconnecting' or 'closed'. Both return status() and close(); WebSockets add send(data).

toast

phApp.toast('Customer saved');
phApp.toast("Couldn't save the customer", { tone: 'error' });
const dismiss = phApp.toast('Import running', { tone: 'info', duration: 0 });
phApp.toast('Customer archived', { action: { label: 'Undo', onClick: restore } });
OptionDefaultWhat it does
tone'success''success', 'error', 'warning' or 'info'
duration4000 (7000 for errors)Milliseconds before it goes. 0 keeps it until dismissed.
actionnoneOne button: { label, onClick }

Returns a function that dismisses the toast. See Toasts.

dialog

phApp.dialog.open('#edit-customer');
phApp.dialog.close('#edit-customer', 'saved');

const ok = await phApp.dialog.confirm({
  title: 'Archive Olivia Bennett?',
  message: 'They lose access to every store straight away.',
  confirmLabel: 'Archive customer',
  danger: true,
});
FunctionWhat it does
dialog.open(target)Opens a <dialog class="ph-dialog"> or .ph-drawer as a modal and focuses its first field, or the element with autofocus
dialog.close(target, returnValue?)Closes it; returnValue ends up on dialog.returnValue
dialog.confirm({ title, message?, confirmLabel?, cancelLabel?, danger? })Asks a question. Resolves true for confirm, false otherwise. Labels default to "Confirm" and "Cancel". danger makes confirm red and starts focus on Cancel.

See Dialogs and drawers for the markup and the data-ph-open and data-ph-close attributes.

tabs and enhance

  • phApp.tabs.select(tab, focus = false) selects a role="tab" element and shows its panel. Tab lists and segmented controls fire a ph-change event with event.detail.value.
  • phApp.enhance(root?) wires up tabs, menus and data-ph-table tables inside root. The kit watches the page and does this for content you add, so you rarely need it.

Theme

MemberWhat it does
theme()'light' or 'dark'
onThemeChange((mode) => …)Runs when the theme changes. Returns a function that stops listening.
setTheme(mode)'light', 'dark' or 'auto' (follow the device). For apps used outside Performance Hub; inside it, Performance Hub decides.

The kit sets class="light" or class="dark" and color-scheme on <html>. Kit components, charts, calendars and maps update themselves.

Performance Hub connection

MemberWhat it does
embedded()true once Performance Hub has connected to the app
host(){ host: 'performance-hub', features, origin } once connected, else null
onHostReady((host) => …)Runs when Performance Hub connects (straight away if it already has)
ready()Tells Performance Hub the first view is on screen, with <html data-ph-ready="manual">
navigate(path)Opens a Performance Hub page, such as '/customers'. Returns false outside Performance Hub.

See Performance Hub integration.