@devioarts/capacitor-mdns

中文文档
0.2.0发布于 2026/11/07MITTypeScriptESM + CJS零依赖近 30 天下载 3625

mDNS plugin for CapacitorJS

原始使用文档
文档目录17 节
  1. Install
  2. Upgrading from 0.1.0
  3. Usage
  4. Continuous discovery
  5. Platform Setup
  6. API
  7. getPluginPlatform()
  8. startBroadcast(...)
  9. stopBroadcast()
  10. discover(...)
  11. watchServices(...)
  12. stopWatching()
  13. addListener('serviceFound' | 'serviceLost', ...)
  14. addListener('watchError', ...)
  15. removeAllListeners()
  16. Interfaces
  17. Type Aliases

@devioarts/capacitor-mdns

mDNS plugin for Capacitor that supports Bonjour/mDNS advertisements and discovery on iOS, Android, Electron, and a safe web fallback.

Supported Capacitor version: v8. iOS 15 or later is required.

Supported platforms: ✓ iOS ✓ Android ✓ Electron ✓ Web fallback

The in-repository playground is the example app used during development.

Install

npm install @devioarts/capacitor-mdns
npx cap sync

For Electron, also install bonjour-service@~1.4.0 and run npx cap-electron sync. See the Electron setup for details.

Upgrading from 0.1.0

Version 0.2.0 retains the existing method signatures and result shapes and adds continuous discovery. It also tightens input validation, changes overlapping discovery and error handling, and raises the declared iOS minimum to 15.0. Review the upgrade notes before updating an existing application.

Usage

import { mDNS } from '@devioarts/capacitor-mdns';

const runtime = await mDNS.getPluginPlatform();

await mDNS.startBroadcast({ type: '_http._tcp.', name: 'MyService', port: 9100 });
const result = await mDNS.discover({ type: '_http._tcp.', timeout: 3000 });
await mDNS.stopBroadcast();

Continuous discovery

Thank you, Idrimi, for contributing the original continuous discovery feature in PR #7.

watchServices() monitors multiple service types on iOS, Android and Electron until stopped. Register listeners before starting; a new valid call replaces the previous watch.

const found = await mDNS.addListener('serviceFound', ({ service }) => {
  console.log('Found', service.name, service.hosts, service.port);
});
const lost = await mDNS.addListener('serviceLost', ({ service }) => {
  console.log('Lost', service.name, service.hosts, service.port);
});
const errors = await mDNS.addListener('watchError', (event) => {
  console.error(event.type, event.errorMessage, event.watching);
});

const result = await mDNS.watchServices({
  types: ['_http._tcp.', '_airplay._tcp.', '_googlecast._tcp.'],
});
// Later, including when leaving the screen:
await mDNS.stopWatching();
await Promise.all([found.remove(), lost.remove(), errors.remove()]);

Found/lost events contain the full service snapshot; hosts is always an array. A service that disappears before resolving emits neither event. Browser errors stop watching and emit watchError with watching: false; exhausted resolution retries emit it with watching: true. stopWatching() leaves broadcasting and one-shot discovery running. Browsers do not support mDNS.

Platform Setup

Android requires mDNS/network permissions in AndroidManifest.xml; the plugin also declares them so they are merged during sync. iOS requires local network keys in Info.plist. Electron support is intended for devioarts/capacitor-electron and uses metadata exported from @devioarts/capacitor-mdns/electron/settings.

Detailed setup lives in:

API

Public API surface of the Capacitor mDNS plugin.

getPluginPlatform()

getPluginPlatform() => Promise<MdnsPluginPlatformResult>

Return the platform implementation currently serving plugin calls.

Returns: Promise<MdnsPluginPlatformResult>


startBroadcast(...)

startBroadcast(options: MdnsBroadcastOptions) => Promise<MdnsBroadcastResult>

Start advertising a Bonjour/mDNS service.

ParamTypeDescription
optionsMdnsBroadcastOptions- {@link MdnsBroadcastOptions}

Returns: Promise<MdnsBroadcastResult>


stopBroadcast()

stopBroadcast() => Promise<MdnsStopResult>

Stop advertising the currently registered service (no-op if none).

Returns: Promise<MdnsStopResult>


discover(...)

discover(options?: MdnsDiscoverOptions | undefined) => Promise<MdnsDiscoverResult>

Discover services of a given type and optionally filter by instance name.

ParamTypeDescription
optionsMdnsDiscoverOptions- {@link MdnsDiscoverOptions}

Returns: Promise<MdnsDiscoverResult>


watchServices(...)

watchServices(options: MdnsWatchOptions) => Promise<MdnsWatchResult>

Continuously watch several service types. A valid call replaces the previous watch. Register listeners before starting. Each resolved service emits serviceFound once; disappearance emits serviceLost with its last snapshot. No loss is emitted for an unresolved service. Watching and one-shot discovery can run together. Thanks to Idrimi for contributing the original continuous discovery feature (PR #7).

ParamType
optionsMdnsWatchOptions

Returns: Promise<MdnsWatchResult>


stopWatching()

stopWatching() => Promise<MdnsWatchStopResult>

Stop all watchers. No events from that watch are emitted after this resolves.

Returns: Promise<MdnsWatchStopResult>


addListener('serviceFound' | 'serviceLost', ...)

addListener(eventName: 'serviceFound' | 'serviceLost', handler: (event: MdnsServiceEvent) => void) => Promise<PluginListenerHandle>
ParamType
eventName'serviceFound' | 'serviceLost'
handler(event: MdnsServiceEvent) => void

Returns: Promise<PluginListenerHandle>


addListener('watchError', ...)

addListener(eventName: 'watchError', handler: (event: MdnsWatchErrorEvent) => void) => Promise<PluginListenerHandle>
ParamType
eventName'watchError'
handler(event: MdnsWatchErrorEvent) => void

Returns: Promise<PluginListenerHandle>


removeAllListeners()

removeAllListeners() => Promise<void>

Interfaces

MdnsPluginPlatformResult

Result of getPluginPlatform(). Useful for validating that calls are routed through the expected platform bridge.

PropTypeDescription
platformMdnsPluginPlatformPlatform implementation that produced this result.

MdnsBroadcastResult

Result of startBroadcast(). Indicates whether advertising is active and the final service name. On failure, error is true and errorMessage describes the issue.

PropTypeDescription
errorbooleanTrue if the operation failed.
errorMessagestring | nullError description or null on success.
namestringFinal (possibly uniquified) service instance name. Empty on failure.
publishingbooleanWhether an advertiser is active, or may still be active after failed cleanup.

MdnsBroadcastOptions

Options for starting a Bonjour/mDNS advertisement.

PropTypeDescription
typestringService type (including the trailing dot).
namestringService instance name (maximum 63 UTF-8 bytes). Defaults to DevIOArtsMDNS.
portnumberTCP port to advertise.
txtMdnsTxtOptional TXT key–value pairs (UTF-8 strings).

MdnsStopResult

Result of stopBroadcast(). Indicates whether the advertiser is active after the call (normally false) and includes error information.

PropTypeDescription
errorbooleanTrue if an error occurred while stopping.
errorMessagestring | nullError description or null on success.
publishingbooleanFalse after confirmed stop; true when stopping failed and the advertiser may still be active.

MdnsDiscoverResult

Result of discover(). Contains normalized services and error information.

PropTypeDescription
errorbooleanTrue if discovery encountered an error (partial results may still be present).
errorMessagestring | nullError description or null when no error occurred.
servicesFoundnumberConvenience count equal to services.length.
servicesMdnsService[]Resolved services with numeric addresses. Empty on error; partial results are discarded.

MdnsService

Normalized description of a discovered Bonjour/mDNS service. Returned from {@link mDNSPlugin.discover}.

PropTypeDescription
namestringInstance name of the service (may be uniqued by the OS, e.g. "My App (2)").
typestringFull service type including the trailing dot, e.g. "_http._tcp.".
domainstringService domain; typically "local.".
portnumberPort the service advertises.
hostsstring[]Resolved numeric IP addresses, IPv4 first, then IPv6 with any available scope suffix.
hostnamestringHost name when supplied by the platform, e.g. "my-device.local.".
txtMdnsTxtTXT dictionary (key → value).

MdnsDiscoverOptions

Options for Bonjour/mDNS discovery.

PropTypeDescription
typestringService type (including the trailing dot).
namestringOptional instance name filter (prefix-safe).
timeoutnumberDiscovery timeout in milliseconds. Finite numbers only; fractions are truncated and the delay is clamped to 0–2147483647.
useNWbooleaniOS-only hint to use NWBrowser instead of NetServiceBrowser.

MdnsWatchResult

Native browsers have been requested; later failures are reported through watchError.

PropType
errorboolean
errorMessagestring | null
watchersStartednumber

MdnsWatchOptions

Options for continuous discovery on iOS, Android and Electron.

PropTypeDescription
typesstring[]Nonempty list of service types. Trailing dots are optional; duplicates are merged.

MdnsWatchStopResult

Stops watching independently of any active broadcast.

PropType
errorboolean
errorMessagestring | null
watchingboolean

PluginListenerHandle

PropType
remove() => Promise<void>

MdnsServiceEvent

Both found and lost events contain a complete service snapshot, including hosts.

PropType
serviceMdnsService

MdnsWatchErrorEvent

Browser failures stop the watch; exhausted service resolution retries leave it running.

PropType
typestring
errorMessagestring
watchingboolean

Type Aliases

MdnsPluginPlatform

Runtime implementation that handled a plugin call.

'ios' | 'android' | 'electron' | 'web'

MdnsTxt

Key–value map for TXT records of a Bonjour/mDNS service. Values are UTF-8 strings; binary payloads are not supported by this API.

Record<string, string>

Record

Construct a type with a set of properties K of type T

{ [P in K]: T; }

版本与发布记录

@devioarts/capacitor-mdns 共发布 4 个版本,首次发布于 2025/09/03;过去 12 个月发布了 3 个版本。

版本发布日期距今
0.2.0latest2026/11/075 天前
0.1.02026/07/084 个月前
0.0.32026/06/105 个月前
0.0.22025/09/031.2 年前

关于 @devioarts/capacitor-mdns 的常见问题

@devioarts/capacitor-mdns 是什么?

mDNS plugin for CapacitorJS

如何安装 @devioarts/capacitor-mdns?

在项目目录运行 npm install @devioarts/capacitor-mdns,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(^8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@devioarts/capacitor-mdns 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@devioarts/capacitor-mdns 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@devioarts/capacitor-mdns 可以商用吗?

@devioarts/capacitor-mdns 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@devioarts/capacitor-mdns 的下载量有多少?

根据 npm 官方下载统计,@devioarts/capacitor-mdns 在 2026/10/12 – 2026/11/10 这 30 天内被下载 3,625 次,日均约 121 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@devioarts/capacitor-mdns 还在维护吗?

最新版本 0.2.0 发布于 2026/11/07(5 天前);至今共发布 4 个版本,其中过去 12 个月发布了 3 个;首次发布于 2025/09/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。