Documentation

JavaScript bridge reference

The public API for HTML to App 1.1.1. Handle Finder documents, build widgets that avoid the system Dock, and control an exported app's own Dock icon.

Package format · JavaScript bridge · Plain-text project guide

Detect the host and the permission

This reference describes HTML to App 1.1.1. Updating the builder does not update apps you already exported. Re-export with 1.1.1 or later to choose whether an app starts in the Dock, change its Dock icon visibility, or read the system Dock's position.

The namespace is exactly window.HTMLtoApp. Desktop APIs are provided to the local project's main document. Do not call private WebKit message handlers. A regular browser does not have this bridge. Feature-detect the specific method and handle rejected promises instead of assuming an installed app, a permission grant, or an OS version.

const api = window.HTMLtoApp;
const preview = api?.isPreview === true;
const canPlaceWindow = typeof api?.window?.setBounds === "function";
const cameraPreview = preview && api?.previewCapabilities?.camera === true;

Preview uses the builder's identity. The Mac App Store edition does not offer camera, microphone or location in Preview. A Setapp Preview that advertises the corresponding previewCapabilities.camera, .microphone or .location can request it. Feature flags are not user consent. In an export, enable the selected capability and request it from a relevant user action with navigator.mediaDevices.getUserMedia() or navigator.geolocation. Handle missing hardware, denial and cancellation. Stop media tracks when finished.

The exported site normally loads from htmltoapp://site/index.html. A workspace project can have a different local scheme. Resolve resources relative to the document, never by hardcoding either scheme or a file path. Test Finder registration, the exported app's own permissions, its Dock artwork and its stored data in an actual export.

The bridge does not expose a shell, arbitrary filesystem paths, native Calendar or Contacts access, or a general way to call macOS APIs. Do not invent methods such as HTMLtoApp.openExternal() or HTMLtoApp.showSaveDialog(). Use ordinary links or a user-initiated download as described below.

Link to another project page with a relative URL. A top-level link to an external HTTP or HTTPS website opens in the Mac's default browser, not in the project window. A local link with target="_blank" loads in the existing project window. Do not use window.open() to create a second independent app window. Project links to mailto: or another app's custom URL scheme are blocked. To request that an installed app open, use the permission and user action described under installed applications. Fetching data from a web service is a separate operation and still depends on connectivity and CORS.

In Preview and in an export, the View menu provides Reload Page, Back, Forward, Home, Zoom In, Zoom Out and Actual Size. Home returns to the project's entry page. Page zoom changes web content size, not the native window frame. If WebKit's renderer stops, the host attempts a reload. After repeated interruptions it offers a manual reload instead. Save important edits as they happen rather than relying on a page-close handler.

Open files and folders

Finder Open With, Dock drops and later native opens deliver scoped items. On window, listen for htmltoapp-open and then read api.launchItems or api.consumeLaunchItems(). Despite its name, the latter returns a snapshot and does not drain the queue. Use event.detail.items and honor replaceExisting. Handle a cold start, later deliveries and a repeated item. For example, a viewer that keeps one row per document can use this pattern with its own renderRows function.

const rows = new Map();
function receive(items, replace) {
  if (replace) rows.clear();
  for (const item of items) {
    rows.set(JSON.stringify([item.itemId ?? item.id, item.relativePath ?? ""]), item);
  }
  renderRows([...rows.values()]);
}
window.addEventListener("htmltoapp-open", ({detail}) =>
  receive(detail.items, detail.replaceExisting));
receive(window.HTMLtoApp?.launchItems ?? [], false);

Root items contain id, itemId, name, path, relativePath, kind, isDirectory and writable. Files have a loadable url; directories have baseURL and listingURL. An entry from a folder listing can be passed to the bridge by itemId and relativePath. Use api.urlFor(item, relativePath) for scoped media URLs. A displayed path or a cached ID is not a persistent grant. Never build a native URL from an arbitrary path.

api.runtime contains enabled, role, allowFiles, allowFolders and canWriteBack. Listen for htmltoapp-runtime for changes. A drop can provide read access even without Finder file registration. Viewer access does not permit writing back. Preview file operations can affect real files.

All api.fs methods return promises. Omit the relative path to use the item itself. On a folder, provide a relative child path. The following are the public methods.

MethodResult and constraints
stat(item, path?)File or folder metadata, including size for a regular file.
list(item, path?)An object with entries and truncated, not an array. Handle a truncated listing explicitly.
readText(item, path?, options?)Metadata plus text and detected encoding.
readData(item, path?)Metadata plus base64Data and mimeType, not a Blob.
writeText(item, text, path?, options?)Editor write-back. Options include encoding, atomic and createIntermediates. Preserves the detected encoding of an existing text file when possible.
writeData(item, base64Data, path?, options?)Editor write-back with Base64 bytes, not a data URL. Supports atomic and createIntermediates.
createDirectory(item, path, options?)Create a child of a writable folder. Supports createIntermediates.
move(item, fromPath, toPath, options?)Move within the same writable folder. Supports createIntermediates and overwrite. Overwrite defaults to false.
remove(item, path?, options?)Delete, not Move to Trash. Confirm with the user. Deleting a nonempty folder needs recursive: true. The opened root folder cannot be deleted.

Read (await api.fs.readText(item)).text. Before modifying anything, check api.runtime?.canWriteBack, the item's writability, and the actual operation result. Atomic writes and intermediate directories default to enabled. Bridge file data is limited to 64 MiB per read or write, text writes to 16,777,216 UTF-16 units, a listing to 4,096 entries and opened items to 128. Relative paths are limited to 4,096 UTF-16 units and 256 components. Prefer a scoped URL for media playback instead of reading a video into Base64.

An HTML file input returns browser File objects, not native items. Use file.text(), object URLs or standard file APIs with those objects. A folder picker can use a separate webkitdirectory input when supported. To save a copy without Editor permission, create a Blob URL and activate an anchor with a suggested download filename. Release the URL after the download has started. The native save panel can be cancelled, so do not announce a successful disk write merely because the link was clicked. There is no public arbitrary-path or shell API.

Text encodings and errors

readText detects the encoding. Passing an encoding option does not force decoding. For an explicit writeText encoding use utf-8, utf-16, utf-16le, utf-16be, iso-8859-1 or windows-1252. When editing a file in place, omit the option to preserve its encoding when possible.

File operations reject with an Error that can carry error.code. For opened_item_missing, let the user reopen the document. For write_back_not_allowed, offer Save a Copy. For file_too_large, offer a smaller input or a scoped media URL. For unsupported_encoding, offer a supported output encoding without overwriting the original. These codes are not exhaustive. Show a useful fallback for other failures and report saved changes only after a successful write.

Window placement, shape and displays

Use api.setWindowTitle(title), api.hideWindow(), api.showWindow() and api.quit() for simple commands. They do not return confirmation promises. In Preview, quit closes the preview, not the builder. In an exported app it quits that app. The host also handles the standard window.close() request. Closing a window is not the same as quitting the app. For placement and desktop widgets, use api.window.

Window methodBehavior
getState()Resolves to the current options plus bounds, displayId, minimized, zoomed, fullscreen and userRestored.
getDisplays()Resolves to entries with id, name, bounds, visibleBounds, scale and primary.
configure(options)Merges the supplied options and resolves to the resulting state. Unknown keys or values reject.
setBounds({x, y, width, height})Changes supplied fields in logical screen points. Use the returned state for the actual bounds after fitting or anchoring.
moveToDisplay(id)Moves the one interactive window to a connected display.
startDrag({snapToEdge: true})Starts a real user drag. Prefer an HTML grip with data-htmltoapp-drag or data-htmltoapp-drag="snap". Buttons and fields are excluded.
setShape(source), setShape(null)Apply an alpha mask from a local image, canvas or PNG data URL, or return to tracking HTML regions.
refreshShape()Schedules recalculation of tracked HTML regions after custom drawing or transforms.
close(), minimize(), zoom(), toggleFullScreen()Native window actions. Zoom is not fullscreen. For fullscreen entry, use a titled window without all-Spaces mode.
reset()Restore the standard frame, decoration, input policy and level.
deferInitialPresentation()Synchronously returns a release function. Call before the first startup await and release in a finally block. It does not extend the export's roughly two-second first-window timeout.

The origin is the upper left of the primary display, with positive y down. Displays to its left or above can have negative coordinates. visibleBounds excludes the Dock and menu bar. Display IDs are session values. Listen on window for htmltoapp-displayschange with detail.displays and htmltoapp-windowchange with the new state in detail.

Configuration keySupported values
titleBarstandard, overlay or borderless. Overlay keeps native buttons over the content.
levelnormal, floating or desktop. Floating is above ordinary windows, not system security UI.
transparent, allSpacesBooleans. Virtual Spaces are independent of physical displays.
clickThroughnever, transparent or always. Always makes the whole window ignore the mouse.
anchor, insetnone, left, right, top, bottom, topLeft, topRight, bottomLeft, bottomRight. Inset is 0 to 512 points.
displayMode, mirrorInteractionsingle or mirror. Mirror interaction is moveHere, activateHere or ignore.
missionControlnormal or stationary. Stationary asks macOS to keep the widget in place.

Enable transparent: true before setting a shape and leave the page background clear where the desktop should show. With clickThrough: "transparent", mark the interactive surfaces with data-htmltoapp-region or data-htmltoapp-region="ellipse". The renderer tracks up to 128 marked elements, or direct body children if none are marked. This is not pixel testing of every CSS effect. For an irregular silhouette or interior holes, pass a canvas or a local image to setShape. A direct PNG mask must be at most 1,024 by 1,024 pixels and its complete Base64 data URL must fit within 2,097,152 characters. If a manual mask changes, submit it again. Use setShape(null) to resume automatic region tracking.

Give a click-through widget a recovery action outside the window, such as a Show Controls item in its menu bar menu. Window > Restore Standard Window or Option-Command-R restores the normal window and locks customization for the current document. While userRestored is true, do not retry or immediately repin. Reloading the project unlocks customization. In contrast, the project's own window.HTMLtoApp.window.reset() restores the frame without imposing that user lock. Window changes can also reject while a sheet or fullscreen transition is active.

// Call from a button. Place data-htmltoapp-region on the visible widget surface.
async function pinWidget() {
  const win = window.HTMLtoApp?.window;
  if (!win) return;
  await win.configure({titleBar: "borderless", level: "floating", transparent: true,
    clickThrough: "transparent", anchor: "right", inset: 8});
  await win.setBounds({width: 240, height: 160});
}

Mirrors are snapshots refreshed up to four times a second, not independent scripts or full-rate video windows. They pause when hidden, minimized, in native fullscreen or displaying a sheet. With moveHere, a click moves the interactive window to that display. With activateHere, it also delivers htmltoapp-mirroractivate with viewport detail.x and detail.y. Use document.elementFromPoint to identify the control. A real click on a mirror can authorize one apps.open request from that handler. Dispatching the same event yourself cannot create a launch gesture. Choose ignore for a display-only mirror.

Find the system Dock

Use await api.dock.getSystemPlacement() to find which display edge to leave free for the macOS Dock. It works in Preview and in an exported app, even when the app has no Dock icon of its own. The query does not require permission to list apps, Accessibility access or Screen Recording.

FieldWhat it tells you
displayIdThe Dock's current display. Match it to an id from api.window.getDisplays(), not to a display name or the primary screen.
edge and orientationA bottom Dock is bottom and horizontal. A side Dock is left or right and vertical.
estimatedHeight and estimatedWidthThe estimated thickness in screen points. Only height applies to a bottom Dock and only width to a side Dock. This is not the length of the Dock or the size of its icons.
reservedAreaWhen macOS reserves one identifiable strip, this is {displayId, edge, thickness}. After the Dock moves, the strip may still be on the previous display.

Unknown fields are null, not zero. An auto-hidden Dock may have no detectable location. If the current Dock and the reserved strip disagree, both size estimates are null. For ordinary window placement use the target display's visibleBounds, which already accounts for reserved space. Do not subtract the Dock thickness again.

For example, a shelf that normally sits on the right can choose the left edge when the Dock occupies the right edge of that same display. Pass the shelf's target display ID, or (await api.window.getState()).displayId for its current display.

async function chooseShelfEdge(displayId) {
  const dock = window.HTMLtoApp?.dock;
  if (typeof dock?.getSystemPlacement === "function") {
    try {
      const placement = await dock.getSystemPlacement();
      if (placement.displayId === displayId && placement.edge === "right") return "left";
    } catch {
      // Keep the default edge if the host cannot answer.
    }
  }
  return "right";
}

Read the placement when showing or repositioning the shelf and after htmltoapp-displayschange. Moving the Dock between connected displays does not always change the display arrangement. There is no Dock-moved event or background monitor.

Installed applications

Use await api.apps.permissions() to read {list, open, dockArtwork}. Listing and opening are separate, optional user settings in Preview and export. await api.apps.list() returns eligible applications in accessible Applications folders as {id, name} records. await api.apps.icon(id) returns a small PNG data URL or null for an unavailable app. Both calls require listing access. Fetch icons for displayed rows rather than every app at once.

await api.apps.open(id) requests an installed bundle identifier, not a path, URL, command or argument list. Call it directly from a button activated by a real left click, Return or Space in the active project window. Each gesture can authorize one request and expires after one second. Load the list and icons before the click, not between the click and the launch. A timer or a synthetic DOM click cannot supply that gesture.

The native confirmation identifies the target. Allow Once permits that launch. Allow Any App skips more confirmations for the current document, not the gesture requirement. Reloading, navigating or closing ends that consent. Cancel resolves to false, success to true, and unavailable targets or disallowed requests reject. A tool that only opens a known app need not enumerate installed apps.

For example, give a real HTML button and a visible status element to this function. Supply an ID from the list or a known bundle identifier. A cancellation is not an error.

async function wireLaunchButton(button, status, id) {
  const apps = window.HTMLtoApp?.apps;
  button.disabled = true;
  if (typeof apps?.permissions !== "function" || typeof apps.open !== "function") {
    status.textContent = "Open this project in HTML to App to launch apps.";
    return;
  }
  try {
    if (!(await apps.permissions()).open) {
      status.textContent = "Enable Open Installed Apps for this project.";
      return;
    }
  } catch {
    status.textContent = "App launch permission is unavailable.";
    return;
  }
  button.onclick = async () => {
    try {
      const opened = await apps.open(id);
      status.textContent = opened ? "App opened." : "Launch cancelled.";
    } catch (error) {
      status.textContent = error?.message || "Could not open the app.";
    }
  };
  button.disabled = false;
}

Show or hide the Dock icon

An exported app normally starts with a Dock icon. For a menu bar utility, put the following in the entry page's <head>. Export reads it before the app launches, so the icon never has to appear just to be hidden. Omit the tag or use content="true" for the default. Re-export after changing it, even for a linked folder. The tag does not hide the window or create a menu bar item.

<meta name="htmltoapp:dock-visible" content="false">
MethodBehavior
await api.dock.isVisible()Reports whether the running export shows its Dock icon. Always returns false in Preview.
await api.dock.setVisible(true) or await api.dock.setVisible(false)Shows or hides the running app's icon without opening or hiding its window. Pass a boolean. Resolves to true on success, including when already in the requested state. Preview rejects the request and leaves the builder's icon alone.

The choice lasts until the app quits, including across page reloads and window changes. The next launch uses the metadata again. Do not gate Show Dock icon on dock.isAvailable(). That checks whether artwork can be drawn on a visible icon. Hiding the running icon also takes the app out of the app switcher, but does not remove a shortcut the user pinned to the Dock. Give menu bar users Show Window and Quit actions.

To try it, create a fresh Menu Bar Controls project from the gallery and export it. Open the app, choose Show Dock icon, then click the icon to see the reopen event in the example's log. Choose Hide Dock icon and the window stays open. If a project instead calls api.hideWindow() on its only window, the export stays running. Reopen it in Finder or click its visible Dock icon to bring the window back.

Live Dock artwork, badges and notifications

Call this example from a Notify Me button. A result of "requested" is not proof that the person saw a notification.

async function requestNotice(title, body) {
  if (!("Notification" in window)) return "unavailable";
  const permission = Notification.permission === "default"
    ? await Notification.requestPermission()
    : Notification.permission;
  if (permission !== "granted") return permission;
  new Notification(title, {body});
  return "requested";
}

api.menuBar.configure(options) sets status item behavior. Use setIcon(optionsOrImage), setTitle(text), setTooltip(text), hideIcon(), setBadge(value) and clearBadge() on that namespace. Icon options include title, tooltip, image, imageVisible, imagePosition (left or right) and template. Use a small local PNG encoded as a data URL for custom artwork.

Use visible to show or hide the item, openMenuOn to choose the mouse button and showWindowOnClick to control window activation. An exported app can include or omit its native menu actions with defaultMenuItems. Preview shows the project's menu items instead. The same options object can include closeToMenuBarOnWindowClose, badge, menu, onClick and onItemClick. A menu bar badge is drawn on the image. It does not add a count to a text-only title.

setMenu(itemsOrProvider) accepts an array or a provider function. The provider may return an array or an object with an items array, directly or as a promise. The host can ask for the menu when the provider is registered as well as when the menu opens, so keep the provider free of side effects. Give actions stable id and title values. Items support enabled, hidden, checked (or state: "on"), toggle, a single-character keyEquivalent (or key), nested submenu arrays (or items) and {type: "separator"}. Use setOpenMenuOn("left" | "right" | "middle" | "other" | "any" | "none") to choose the trigger and closeMenu() to dismiss it.

onClick(handler) and onItemClick(handler) return unsubscribe functions. The callbacks receive payloads directly. The DOM equivalents are htmltoapp-menubar-click and htmltoapp-menubar-item-click, with the payload in event.detail. Register one mechanism, not both for the same action. Menu item payloads include id, title, checked, state, toggle and path. Status clicks include button, hasMenu and willOpenMenu.

With a visible status item, setCloseToMenuBarOnWindowClose(true) lets an export stay in the menu bar when the user closes its window. Without an explicit dock.setVisible() choice, closing to the menu bar hides the Dock icon and showing the window restores the launch default. This is separate from a project hiding its own window. Neither mechanism installs a daemon or guarantees timers across sleep or after quitting.