npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@primafuture/web-app-launcher

v4.0.0

Published

Typed browser access to the Web App Launcher Android bridge

Readme

@primafuture/web-app-launcher

Typed browser access to the Web App Launcher Android API. Framework-independent ESM / CommonJS JavaScript and TypeScript declarations, with no runtime dependencies.

This source prepares 4.0.0, with prioritized network access/DNS control and native bridge contract 4. It is not published automatically.

SDK 4.0 requires native bridge version 4 and the launcher requires Android 10+. getBridge() returns undefined in ordinary browsers and older launchers. Upgrade launcher and SDK together. There are no compatibility aliases for removed network methods or events.

Network access and DNS

bridge.networkAccess manages only the calling web's deciders and resolvers. Multiple webs share one native engine. Higher priority runs first; equal priority retains first-registration order. Flow allow/deny are terminal and pass continues. Ask produces a request for its owner, which may decide later. The native user controls global fallbacks (initially allow / system DNS) and whether to include the launcher itself (initially excluded).

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
const pendingRequests = new Map<string, webAppLauncher.FlowRequest>();
if (bridge) {
	await webAppLauncher.on(bridge.networkAccess, 'flowrequest', event => {
		// Store the handle, show your own UI, or decide asynchronously.
		pendingRequests.set(event.detail.id, event.detail);
	}, { wake: true, id: 'my-flow-decisions' });
	await bridge.networkAccess.registerFlowDecider({
		id: 'interactive',
		priority: 100,
		match: { applications: { mode: 'include', packages: ['com.example.app'] } },
		action: 'ask',
		timeoutMs: 15_000,
		onTimeout: 'deny',
	});
	await bridge.ready();
	// First grant installation access in Launcher → Permissions.
	await bridge.networkAccess.enable();
}

After a decision, call request.allow(), deny() or pass(); these return Promises. getPendingFlowRequests() returns equivalent handles after reload; resolveFlowRequest({id, action}) is the ID-based form. Handler completion only acknowledges event delivery. It does not allow a flow. A permanent application exception requires an explicit rule, not an extra option on allow(). disable() disables only this web's policy.

DNS uses registerDnsDecider() and dnsrequest; actions are resolve/respond/block/pass/ask. Request methods are resolve({resolverId?}), respond({records}), block({responseCode?}) and pass(). setResolvers() replaces owner-local system/UDP/TCP/TLS/HTTPS definitions. TLS/HTTPS require a numeric bootstrap address and verified serverName; HTTPS additionally requires url. Own records support A/AAAA/CNAME and TTL. No hidden resolver fallback or inspection of foreign encrypted DNS is promised.

getPolicy, getState, getCapabilities, getApplications, getStats, removeDecider, getPendingDnsRequests and resolveDnsRequest complete the namespace. Events also include statechange, policychange and requestfinished. Standard listener wake/id/once/signal behavior applies. Rules survive sleeping/reloading/quitting the controller; pending requests survive its document, not native engine death. Deadlines/capacity use configured native fallback without waiting indefinitely for JavaScript.

All network-access operations require Allow device access in addition to JS interface. Installation consent is separate and cannot be granted by a web. Android shows its VPN consent/indicator and permits one active service in the profile; filtering does not switch off radios, cover hotspot clients or guarantee blocking through native service death. Use native Network access controls if you disconnect the controller itself.

See the full behavior, limits and independent tester handoff and public types.

Network information and migration to 3.0

Replace bridge.getNetworkStatus() with bridge.network.getState(), the root networkChanged event with namespace statechange, and capability networkStatus with network. Old saved networkChanged wake registrations and their pending deliveries are removed on upgrade; re-register the new source before ready().

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
if (bridge) {
	const stop = await webAppLauncher.on(bridge.network, 'defaultchange', async event => {
		console.log(event.detail.previousNetworkId, event.detail.networkId);
	}, { wake: true, id: 'default-connection' });
	await bridge.ready();
	console.log(await bridge.network.getState());
	console.log(await bridge.network.getNetworks());
	console.log(await bridge.network.getWifiState());
	console.log(await bridge.network.getCellularState());
	// Explicitly unsubscribe when this persistent rule should be removed.
	// await stop();
}

All namespace methods return Promises. getCapabilities() reports feature/permission availability. getState() describes the launcher's default network, with initializing, defaultNetworkId, transport list, connected, internetCapable, validated, metered and captivePortal. Connected or validated does not prove that your backend is reachable, especially with a VPN/firewall.

getNetworks() returns current Android networks visible to the launcher, not a scan of nearby Wi-Fi. getNetwork(id) returns the same detail for one temporary ID or rejects with NETWORK_NOT_FOUND after it disappears. Details include transports, default selection, capabilities, UID-specific blocking where supported, local IPv4/IPv6 addresses with prefixes, routes/gateways, DNS/Private DNS, proxy, MTU, system bandwidth estimates and available Wi-Fi details. These are passive snapshots, not public-IP lookups or speed tests. IDs must not be persisted as identities of Wi-Fi networks or SIMs.

getWifiState() separates adapter state from its connections, including available SSID/BSSID, RSSI, signal level, frequency/band, standard and link rates. getCellularState() separates the mobile-data user setting from actual connection state and returns available active subscriptions, default data subscription, slot/name/carrier, roaming, radio technology and signal. LTE/NR values describe the reported radio technology, not the status bar's marketing 5G indicator. No phone number, IMEI, IMSI or SIM serial number is exposed.

Unknown, unsupported or redacted fields use null and an unavailable reason keyed by field/group. An accessible empty list means no matching entries; a null list means unavailable. Capability flags describe permission prerequisites, not a guarantee that Android supplies each field. Values vary by Android release and hardware: blocked status requires API 29+, and network-to-subscription associations require API 35+. Allow device access gates Wi-Fi identity and SIM details. Android permissions remain separate: use Launcher → Permissions for Wi-Fi identity/precise location and Mobile network information. Android can hide Wi-Fi identity in the background; wake payloads conservatively require background location access for identity fields. Read operations do not request permissions or turn radios on.

Events are statechange (summary), defaultchange (previous/new IDs), networkchange (kind, networkId, network; removed includes last detail), wifistatechange and cellularstatechange. They support the same listener options, wake queue and async handler acknowledgements as other namespace events. Initial monitor data is a baseline; permission/source changes and new connections generate updates. Detailed signal changes may be frequent, so choose wake sources deliberately. Persistent monitoring depends on the native process/foreground monitor and does not replay changes missed while that process was absent. No polling, scan, permanent CPU wake lock or connection request is used.

openSettings('internet' | 'wifi' | 'cellular' | 'vpn') requires a visible web window and confirms opening a system screen, not changing a setting. If the selected screen is absent, generic wireless settings are used. Other failures include INVALID_ARGUMENT, WEB_SUSPENDED, WEB_NOT_VISIBLE, ANDROID_PERMISSION_DENIED, NETWORK_UNAVAILABLE and document/lifecycle errors common to the bridge. Missing optional metadata permissions normally return partial data rather than rejecting the entire snapshot.

Native location (SDK 1.5.0)

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
const location = bridge?.location;
if (bridge && location) {
	location.addEventListener('position', event => {
		console.log(event.detail.position);
	});
	await bridge.ready();
	await location.requestAccess({ accuracy: 'precise' });
	const tracking = await location.startTracking({
		mode: 'persistent',
		priority: 'balanced',
		intervalMs: 5000,
	});
	// Read on startup/resume and whenever your consumer is ready.
	const records = await location.getQueuedRecords({ limit: 100 });
	// This example consumes records by logging. For uploads, await server acknowledgement instead.
	for (const record of records) {
		console.log(record);
	}
	await location.acknowledgeRecords(records.map(record => record.id));
	await location.stopTracking(tracking.id);
}

foreground (default) pauses when hidden. background continues while the document exists but stops on Suspend/reload. persistent collects natively through Suspend and reload, stores positions before live delivery, and attempts recovery after process death. It does not keep JavaScript awake. Quit stops native resources; reopening does not restart them.

getState, getLastPosition, getCurrentPosition (including AbortSignal), independent tracking sessions, passive mode, accuracy/interval/distance/batching options, acknowledged bounded queues and persistent enter/exit/dwell regions are available. Check getState for actual grants and geofencing support. Google services are optional for positioning and required for geofencing. Background location permission and background service starts remain subject to Android rules; approximate access may be granted even when precise access is requested. Full behavior: docs/location-contract.md in the repository.

Power status API

Supporting launchers expose capability powerStatus and optional Promise method getPowerStatus(). Read batteryPercent (0–100 or null), externalPowerConnected (boolean or null), powerSource, batteryStatus and powerSaveMode. Subscribe with on('powerStatusChanged', listener) before ready() to receive the initial full snapshot and subsequent changes. Resume supplies the current state rather than a history of changes during Suspend. External power is distinct from actual battery charging, and power saver is distinct from Doze. See the full power contract.

Installation

npm install @primafuture/web-app-launcher

Get the bridge

import * as webAppLauncher from '@primafuture/web-app-launcher';

const webAppLauncherBridge = webAppLauncher.getBridge();

if (webAppLauncherBridge) {
	await webAppLauncherBridge.showNotification({
		body: 'New message',
		data: { threadId: 'alice' },
	});
}

getBridge() returns the original window.WebAppLauncher object or undefined. It returns undefined during SSR, in a regular browser, when JS interface is disabled, outside the configured origin, or when the object does not expose the compatible contract. Importing the package does not access the DOM. Detection checks version 4, the basic getCapabilities, ready and showNotification methods, events.on and the core network and network-access getters; it is not exhaustive validation of arbitrary objects.

The function reads the current object on each call and never invokes native methods. It adds no fallback or mock bridge. Native availability does not guarantee permission or success for every operation.

Events and readiness

Attach listeners before calling ready(). The package never calls it automatically.

import * as webAppLauncher from '@primafuture/web-app-launcher';

const unsubscribe = await webAppLauncher.on('notificationClick', event => {
	// Validate your own application payload before using it.
	console.log(event.detail.id, event.detail.actionId, event.detail.data);
});

const webAppLauncherBridge = webAppLauncher.getBridge();
if (webAppLauncherBridge) {
	await webAppLauncherBridge.ready();
}

// On component/page-owner cleanup:
await unsubscribe();

SDK 2.0 makes every on() registration and unsubscribe asynchronous. Await registration before ready(). Ordinary listeners use the original native CustomEvent with typed detail. No native operation runs during import. In a browser/SSR, ordinary subscriptions remain available; wake: true rejects when the native bridge is unavailable.

const stop = await webAppLauncher.on('powerStatusChanged', async event => {
	await updatePowerPolicy(event.detail);
}, { wake: true, id: 'power-policy' });

// Namespace events use the same mechanism:
const stopBluetooth = await webAppLauncher.on(webAppLauncherBridge.bluetooth,
	'deviceconnectionchange', async event => {
		console.log(event.detail, event.delivery);
	}, { wake: true, id: 'car-connection' });

Wake registration IDs are stable across reloads. Reattach callbacks with the same IDs before ready(). The successful return/completion of the handler acknowledges delivery; throw/reject to leave it pending. Delivery may repeat after a crash with the same event.delivery.id: deduplicate irreversible operations. A native wake window lasts up to 30 seconds; acquire/release a launcher wake lock for longer work. once consumes the registration on its first invocation, including a failed invocation. Explicit unsubscribe/abort removes the native registration; destroying the document alone does not remove persistent registrations. Quit pauses wake listeners until the web is opened again; manual Suspend keeps them enabled.

Read bridge.events.getSources() for every source's scope and limitations and listWakeListeners() to inspect stored registrations. Sources do not start GPS tracking or preserve sockets/players stopped by Suspend. Android may defer background starts; a registry entry is not a guarantee of immediate execution.

listWakeListeners() also returns paused, dropped and error. error is the last native monitor/wake error code, or null; it is not a live monitor health check. A stored listener and a previous error can coexist. Display the error separately from registration status instead of claiming that registration proves successful background monitoring. Reading this snapshot does not clear it.

Persistent wake listeners use one shared foreground monitor notification. The monitor does not continuously hold a CPU wake lock. Android notification permission may be requested during registration from a visible window.

Internet hotspot

bridge.hotspot.getState(), requestAccess(), start() and stop() return Promises. requestAccess() opens Android's special settings access screen from a visible window. Start/stop use Android's configured SSID and password and wait for the observed enabled/disabled state. Observe changes with await on(bridge.hotspot, 'statechange', handler, options).

Hotspot is global to the phone. Closing or suspending a web does not stop it automatically. WRITE_SETTINGS is not sufficient on every Android version; reflection or privileged tethering restrictions may reject operations. Errors are explicit and a local-only hotspot is never substituted for Internet tethering. An enabled hotspot does not itself prove that upstream Internet is available.

eventNames contains every supported public event:

  • beforeSuspend, resume, back
  • notificationClick, notificationReply
  • displayModeChanged (network events use the network namespace)
  • windowChanged, windowMetricsChanged, windowGesture
  • windowAnimationPropertyFinished, windowAnimationFinished

The original DOM event names still use the webapplauncher: prefix. A Back listener must call event.preventDefault() synchronously to take over the native fallback. Returning a Promise or deciding after await cannot cancel Back.

Notification clicks include id, eventId, optional actionId and the original JSON data. Clicks and replies wait for the native document's ready(), including cold starts. Replies include text and require explicit completeNotificationReply({eventId, status:'sent'|'failed'}); event dispatch alone is not a successful backend delivery.

Native methods

getCapabilities() returns a synchronous snapshot. Every other public bridge method returns a Promise. A Promise may report operation acceptance rather than final completion: window animations complete through the animation events.

| Area | Methods | | --- | --- | | Readiness | getCapabilities, ready | | Icon count | setBadgeCount | | Notifications | showNotification, cancelNotification, completeNotificationReply | | Background work | acquireWakeLock, releaseWakeLock | | Device | haptic, vibrate, cancelVibration, keepScreenOn | | Network | network.getCapabilities, getState, getNetworks, getNetwork, getWifiState, getCellularState, openSettings | | Sharing and speech | share, speak, stopSpeaking, getVoices | | System bars | getDisplayMode, setDisplayMode | | Windows | showWindow, hideWindow, getWindow, setWindow, getWindowMetrics | | Animations and units | animateWindow, cancelWindowAnimation, convertUnits |

setBadgeCount(count) only stores the count shown in the launcher list and updates the pinned web shortcut bitmap where supported (99+ above 99, zero restores the plain icon). It does not post or cancel Android notifications and needs no notification permission. Use showNotification() explicitly to post a notification.

All input/result/event types are exported from the package root, including WebAppLauncherBridge, Capabilities, NotificationOptions, NotificationClick, NotificationReply, WindowState, WindowMetrics, WindowAnimationOptions and EventDetails. TypeScript requires lengths with explicit dp, px or % for geometric animation targets and a number for opacity. This package does not validate values at runtime; Android remains authoritative.

Window declarations and applied measurements are separate. WindowState.configuration contains normalized document settings; default contains saved settings. mode can be hidden while the configuration still says app or floating. Metrics distinguish available display, outer window, content and handle, using explicit coordinate spaces. Browser metrics / CSS scale may be null; a hidden handle has null metrics. measured:false can indicate retained measurements after detachment.

Unit conversion changes one length, not its coordinate origin. It does not add or subtract handles, padding or system bars. Percent conversion requires a reference. Window operations, fullscreen, wake locks, screen-on and notification permissions remain subject to Android restrictions. Suspend does not guarantee stopping Web Workers.

Errors

Native errors are passed through unchanged. NativeError documents the optional string code; some platform errors have only a message. Unknown future codes must not be treated as success. A successful getBridge() is not a permission grant. In particular, overlay and notification requests can still fail.

Development

npm ci
npm run typecheck
npm run build
npm pack

For local installation before a registry release:

npm install /path/to/primafuture-web-app-launcher-4.0.0.tgz

npm pack typechecks and builds first. The tsup build cleans dist and produces ESM (index.mjs), CommonJS (index.cjs), format-specific declarations and JavaScript source maps with embedded sources. The archive also contains this README and the ISC license. No Node.js APIs or framework dependencies are used at runtime. Consumers using TypeScript declarations need DOM library types.

The diagnostic web in this repository uses this package through a local file: dependency. Install package development dependencies first; its build then builds the package before checking and bundling the web.

License: ISC. Copyright PrimaFuture.cz s.r.o.; see LICENSE.

Shortcut icon overlays

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
const canvas = document.querySelector<HTMLCanvasElement>('#status-icon');
if (bridge?.getCapabilities().iconOverlay && canvas) {
	await bridge.setIconOverlay(canvas.toDataURL('image/png'));
	await bridge.setBadgeCount(3);
	// Remove only the overlay; the original icon and count remain.
	await bridge.setIconOverlay(null);
}

setIconOverlay(image: string | null): Promise<boolean> stores a transparent PNG over the web app's original shortcut icon. Layers are drawn in this order: original icon, overlay, numeric badge. Set the count to zero to hide only the number. Placement is controlled by the image itself, which fills the icon square. Use a square PNG data URL (data:image/png;base64,…), at most 1024 × 1024 pixels and 1 MiB of PNG bytes; 256 × 256 is recommended. URLs and SVG are not accepted. The shortcut is a static bitmap, not an animation.

The overlay persists across reloads, process restarts, settings edits, manifest updates and changes to the original icon. It only affects pinned web shortcuts, not the launcher list, Recent Apps or notification icons, and creates no notification. It can be set before a shortcut is pinned.

true confirms storage; updating existing shortcuts is best-effort, and the Android launcher controls cropping and refresh timing. Native diagnostics record failed shortcut updates. Invalid input, oversized images, decoding or storage failures reject the Promise without replacing the previous overlay. Check the iconOverlay capability before calling on older launcher versions.

Android toast

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
if (bridge?.getCapabilities().toast === true) {
	await bridge.showToast({ text: 'Saved', duration: 'short' });
}

showToast(options) returns Promise<boolean>: true confirms submission to Android, not visibility or completion. text must be a nonblank string. Optional duration is short (default) or long. Invalid arguments reject with INVALID_ARGUMENT; a suspended document rejects with WEB_SUSPENDED. No additional Android permission is required. Active background documents may request a toast, subject to Android's limits; this does not wake or show the web app. The system controls appearance and timing. Android 12+ shows the launcher application icon and limits text to two lines. Native logs exclude toast text. Older v2 launchers omit the toast capability, so check it before calling.

Speech from the background

speak() can start speech from an active background document as well as a visible window. It does not open the window or turn on the display. A nonactive document rejects with WEB_SUSPENDED. Existing native audio focus/foreground-service restrictions and media volume apply. Suspend cancels active/queued speech; speech alone does not override the saved Suspend timeout. Use the existing Keep alive or document wake-lock policy when continued background execution is needed. The standard speechSynthesis adapter follows the same native rules.

Actual Android visibility

The launcher may keep Chromium's visibility signal enabled so an active page continues executing in the background. Therefore document.hidden and document.visibilityState do not reliably describe the actual Android presentation. New launchers expose getVisibility(): Promise<VisibilityState> and visibilityChanged, independently of execution/Suspend and focus. Detect support with getCapabilities().visibility === true.

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
if (bridge?.getCapabilities().visibility) {
	const unsubscribe = await webAppLauncher.on('visibilityChanged', (event) => {
		console.log(event.detail.visibility); // 'visible' | 'hidden'
	});
	await bridge.ready();
	console.log(await bridge.getVisibility());
	// Call await unsubscribe() when this listener is no longer needed.
}

Register listeners before ready() to receive the initial snapshot. Subsequent events describe state changes. Hidden includes background/unattached presentation, a transparent or temporarily hidden floating panel, and a screen that is off or locked. A floating web can remain visible while its Activity is backgrounded. Visibility does not prove focus or absence of covering windows. During Suspend, intermediate transitions are not replayed; Resume supplies current state. Standard browser visibility properties/events are unchanged. SDK support is additive; older Android launchers can lack this capability/method.

Native audio (SDK 1.2.0)

Check capabilities: this SDK adds types and state subscriptions for newer launcher builds; it cannot add Android support to a normal browser or older launcher.

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
if (bridge?.getCapabilities().nativeAudio) {
    const sound = await bridge.createAudio({
        src: '/sounds/message.mp3',
        usage: 'notification',
        respectQuietMode: true,
        output: { type: 'system' },
    });
    sound.volume = 0.5;
    sound.onended = () => console.log('Finished');
    sound.addEventListener('suppressed', event => console.log('Quiet mode', event));
    await sound.play(); // Actual start; completion arrives as ended.
    // Call dispose when the owning feature is finished, not immediately after play:
    // await sound.dispose();
}

NativeAudio is an EventTarget with load/play/pause, pauseAsync/stop/dispose, seek, volume/mute, loop, playbackRate and normal event names/on... handlers. It is not HTMLAudioElement or a Web Audio source. Assignments are asynchronous; setVolume/seek/setPlaybackRate provide confirmation. HTTP(S), Blob/File and blob/data sources are finite files, prepared before playback and bounded to 512 MiB; no live/progressive streaming.

getAudioState/getAudioDevices/getAudioDefaults/setAudioDefaults expose system observations and document defaults. Use on('audioStateChanged', listener) or on('audioDevicesChanged', listener), keep the returned unsubscribe callback. SDK on() manages watchAudioState; raw window listeners must enable/disable it explicitly. Unknown system fields are null.

Purpose, content, focus, optional extra quiet-mode suppression and physical output are independent. Preferred speaker/device is best effort: observe state.routedDeviceId and routechange. Strict physical output rejects before playback (audioStrictOutput=false). No global volume or DND changes are made. respectQuietMode=false cannot bypass Android restrictions.

speak accepts AudioOptions and still resolves after speech completion. Explicit output synthesizes before playback. Suspend cancels playback; navigation disposes it. Complete behavior: docs/audio-contract.md in the repository.

Bluetooth Classic RFCOMM (SDK 1.3.0)

The optional bridge.bluetooth namespace supports RFCOMM clients and servers with standard JS Streams. Check hardware capability and Android permissions separately. This is not BLE/GATT or a navigator.bluetooth polyfill. A compatible Android launcher is required; installing the npm SDK cannot enable native support by itself.

import * as webAppLauncher from '@primafuture/web-app-launcher';

const bridge = webAppLauncher.getBridge();
if (bridge?.getCapabilities().bluetoothClassic && bridge.bluetooth) {
    const bluetooth = bridge.bluetooth;
    await bluetooth.requestAccess({ connect: true });
    const devices = await bluetooth.getPairedDevices();
    const device = devices[0]; // Let the user choose in a real application.
    if (device) {
        const connection = await bluetooth.connect({ deviceId: device.deviceId });
        const writer = connection.writable.getWriter();
        try {
            await writer.write(new TextEncoder().encode('YOUR_DEVICE_COMMAND\r\n'));
        } finally {
            writer.releaseLock();
        }
        const reader = connection.readable.getReader();
        try {
            const result = await reader.read(); // A block, not necessarily a whole response.
            console.log(result.value);
        } finally {
            reader.releaseLock();
            await connection.close();
        }
    }
}

Server example (use a UUID agreed with the peer):

const bluetooth = webAppLauncher.getBridge()?.bluetooth;
if (bluetooth) {
    await bluetooth.requestAccess({ connect: true, advertise: true });
    await bluetooth.requestDiscoverable({ durationSeconds: 120 });
    const server = await bluetooth.listen({
        uuid: '8d962a68-3768-4f2b-9748-c4778038a601',
        name: 'My RFCOMM service',
    });
    const connection = await server.accept({ timeoutMs: 60000 });
    await server.close(); // The accepted connection remains open.
    // Use connection.readable/writable, then:
    await connection.close();
}

startDiscovery() exposes a devices stream and stop/closed; pair() uses Android pairing UI; getServices() performs SDP. Optional requestAccess({backgroundScan:true}) includes scan and handles the extra Android 10/11 background-location requirement (including the Android 11 settings step). Read permissions.backgroundScan from getState; missing legacy background access rejects hidden discovery and stops a scan when hidden, without restricting known-device connections. Connect defaults to standard SPP UUID and secure RFCOMM. secure:false is an explicit compatibility choice; no automatic fallback. AbortSignal cancels pending connect/pair/SDP/accept, and stops discovery throughout its lifetime. It cannot promise to undo Android pairing already in progress.

Respect stream backpressure, use Uint8Array, and implement framing/acknowledgements in your protocol. TextDecoderStream can decode UTF-8 across block boundaries. Successful writes do not confirm commands executed by an accessory. Readable cancellation or writable abort closes the complete connection; there is no half-close. Suspend and navigation close resources; active background operation uses foreground protection but does not implicitly acquire a CPU wake lock. Reconnect belongs to the web. Full behavior and limits: docs/bluetooth-contract.md in the repository.