Capacitor Plugins

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Plugins are how a web app reaches the device. Each plugin is a small package with a typed JavaScript API, a native implementation in Kotlin for Android and Swift for iOS, and often a web fallback so the same code runs in the browser. The mechanism behind the calls is explained on Architecture and the Native Bridge. This page shows the official plugins used by Trailhead with their permission handling, how to choose between official, community and custom plugins, and how to write a custom plugin. Photos taken by the app are covered in the general context of Media Optimization when they must be resized before upload.

Installing and Syncing a Plugin

A plugin is an npm package. After installing it, npx cap sync links the native part into the Android and iOS projects:

npm install @capacitor/camera @capacitor/geolocation @capacitor/preferences
npx cap sync

The versions used in this section are @capacitor/camera 8.2.6, @capacitor/geolocation 8.2.4, @capacitor/preferences 8.0.1, @capacitor/filesystem 8.1.5, @capacitor/network 8.0.1, @capacitor/app 8.1.2, @capacitor/haptics 8.0.2 and @capacitor/splash-screen 8.0.2, all aligned with Capacitor 8.6.0. Always run npx cap sync after adding or removing a plugin and rebuild the native app, because a native dependency changed. Plugins that touch protected resources also need declarations: usage descriptions in ios/App/App/Info.plist (for example NSCameraUsageDescription and NSLocationWhenInUseUsageDescription) and permissions in android/app/src/main/AndroidManifest.xml. Each plugin’s documentation lists the exact entries.

The Official Plugins

Plugin Package Purpose

Camera

@capacitor/camera

Take a photo or pick one from the gallery.

Geolocation

@capacitor/geolocation

Current position and position watching.

Preferences

@capacitor/preferences

Small key-value storage backed by native storage.

Filesystem

@capacitor/filesystem

Read and write files in app-owned directories.

Network

@capacitor/network

Connection status and change events.

App

@capacitor/app

Lifecycle, back button and deep link events.

Haptics

@capacitor/haptics

Vibration and tactile feedback.

Splash Screen

@capacitor/splash-screen

Show and hide the launch screen.

Permissions

Most plugins that use protected hardware expose checkPermissions() and requestPermissions(). The first returns the current state without prompting; the second shows the system dialog. Users can deny, and can change the decision later in system settings, so each feature must handle a refusal gracefully:

import { Geolocation } from '@capacitor/geolocation';

export async function ensureLocationPermission(): Promise<boolean> {
  const current = await Geolocation.checkPermissions();
  if (current.location === 'granted') {
    return true;
  }
  const requested = await Geolocation.requestPermissions();
  return requested.location === 'granted';
}

When the answer is denied permanently, the app should explain why the feature needs access and offer a button that opens the system settings, instead of asking again.

Camera and Geolocation

Camera.getPhoto takes quality, source (camera or photo library) and a resultType. CameraResultType.Uri returns a path the WebView can display through photo.webPath, which avoids moving large base64 strings across the bridge; Base64 and DataUrl are best kept for small images. Geolocation.getCurrentPosition returns position.coords.latitude and position.coords.longitude, and accepts enableHighAccuracy. Both calls are used together in the log-a-hike code below.

Preferences, Filesystem and Network

import { Directory, Encoding, Filesystem } from '@capacitor/filesystem';
import { Network } from '@capacitor/network';
import { Preferences } from '@capacitor/preferences';

await Preferences.set({ key: 'favourites', value: JSON.stringify(['t-1', 't-2']) });
const { value } = await Preferences.get({ key: 'favourites' });

await Filesystem.writeFile({
  path: 'trails.json',
  data: JSON.stringify([]),
  directory: Directory.Data,
  encoding: Encoding.UTF8,
});

const status = await Network.getStatus();
await Network.addListener('networkStatusChange', (change) => {
  console.log('online', change.connected);
});

Preferences is meant for small values such as settings and flags. It is not encrypted, so tokens and credentials belong in secure storage backed by the iOS Keychain and Android Keystore; larger or structured data belongs in files or a database. The offline cache of the trail list uses these plugins on Data, Storage and Networking.

Haptics, App and Splash Screen

import { Haptics, ImpactStyle, NotificationType } from '@capacitor/haptics';
import { SplashScreen } from '@capacitor/splash-screen';

await Haptics.impact({ style: ImpactStyle.Medium });
await Haptics.notification({ type: NotificationType.Success });

await SplashScreen.hide();

The splash screen is shown at launch and can be hidden explicitly once the first data has loaded. Its launch behaviour is configured with the SplashScreen plugin options in capacitor.config.ts. The App plugin also provides the appUrlOpen and backButton events described in Navigation and Routing.

Community Plugins

Features outside the official set come from the community. Good sources are the plugins maintained by Capawesome (capawesome.io), the capacitor-community GitHub organization, and the Capacitor plugin directory in the documentation. Before adopting one, check:

  • the Capacitor major versions it supports, since a plugin built for an older release can fail to build;

  • whether iOS, Android and web are all implemented;

  • recent releases, open issues and who maintains it;

  • the licence, and whether paid tiers apply;

  • the permissions and native dependencies it adds.

The decision between the three kinds of plugin follows a simple path:

flowchart TD need["Need a device feature"] web{"Does a web API do the job on all targets?"} official{"Is there an official Capacitor plugin?"} community{"Is there a maintained community plugin for Capacitor 8?"} useweb["Use the web API"] useofficial["Install the official plugin"] usecommunity["Install the community plugin"] custom["Write a custom plugin"] need --> web web -->|yes| useweb web -->|no| official official -->|yes| useofficial official -->|no| community community -->|yes| usecommunity community -->|no| custom

Writing a Custom Plugin

A custom plugin has four parts: TypeScript definitions, a web implementation, an Android implementation and an iOS implementation. A plugin that will be shared across apps is created as its own package with the generator:

npm init @capacitor/plugin

The generator asks for the plugin name, package id and class name, and produces a project with the TypeScript sources under src/, an android/ folder, an ios/ folder, an example app and build scripts. A small plugin that belongs to one app can instead live inside the app’s own native projects.

The example is a TrailShare plugin that opens the native share sheet for a trail.

TypeScript Definitions and Registration

// src/definitions.ts
export interface TrailShareOptions {
  trailId: string;
  title?: string;
}

export interface TrailSharePlugin {
  share(options: TrailShareOptions): Promise<{ shared: boolean }>;
}
// src/index.ts
import { registerPlugin } from '@capacitor/core';

import type { TrailSharePlugin } from './definitions';

const TrailShare = registerPlugin<TrailSharePlugin>('TrailShare', {
  web: () => import('./web').then((module) => new module.TrailShareWeb()),
});

export * from './definitions';
export { TrailShare };
// src/web.ts
import { WebPlugin } from '@capacitor/core';

import type { TrailSharePlugin, TrailShareOptions } from './definitions';

export class TrailShareWeb extends WebPlugin implements TrailSharePlugin {
  async share(options: TrailShareOptions): Promise<{ shared: boolean }> {
    if (typeof navigator.share !== 'function') {
      throw this.unavailable('The Web Share API is not available in this browser.');
    }
    await navigator.share({ title: options.title, url: `https://trailhead.example.com/trails/${options.trailId}` });
    return { shared: true };
  }
}

The name passed to registerPlugin must equal the native plugin name. unavailable and unimplemented are helpers on WebPlugin that produce the standard rejection errors.

Android Implementation in Kotlin

package com.example.trailhead

import com.getcapacitor.JSObject
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
import com.getcapacitor.PluginMethod
import com.getcapacitor.annotation.CapacitorPlugin

@CapacitorPlugin(name = "TrailShare")
class TrailSharePlugin : Plugin() {

    @PluginMethod
    fun share(call: PluginCall) {
        val trailId = call.getString("trailId")
        if (trailId == null) {
            call.reject("trailId is required")
            return
        }
        // Start an Android share Intent here using the activity from this.activity.
        val result = JSObject()
        result.put("shared", true)
        call.resolve(result)
    }
}

A plugin that lives inside the app project is registered in MainActivity with registerPlugin(TrailSharePlugin::class.java) before super.onCreate runs.

iOS Implementation in Swift

import Capacitor

@objc(TrailSharePlugin)
public class TrailSharePlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "TrailSharePlugin"
    public let jsName = "TrailShare"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "share", returnType: CAPPluginReturnPromise)
    ]

    @objc func share(_ call: CAPPluginCall) {
        guard let trailId = call.getString("trailId") else {
            call.reject("trailId is required")
            return
        }
        // Present a UIActivityViewController for the trail here.
        call.resolve(["shared": true])
    }
}

The jsName must match the name used in registerPlugin, and each method listed in pluginMethods needs a matching @objc function taking a CAPPluginCall. For a plugin that lives inside the app, register an instance from a CAPBridgeViewController subclass with bridge?.registerPluginInstance(TrailSharePlugin()) in its capacitorDidLoad method; a plugin published as a package is discovered by npx cap sync instead. Calls that need user permission add checkPermissions and requestPermissions methods and declare permissions in the plugin annotation; the official plugin sources on GitHub are the best reference for the full pattern.

Trailhead: Log a Hike

The log-a-hike page combines the Camera and Geolocation plugins and the REST API (POST https://api.example.com/v1/trails/{id}/hikes) with a photo upload. The service keeps the plugin calls and the upload together, and the page only calls it:

// src/app/log-hike/hike.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Camera, CameraResultType, CameraSource } from '@capacitor/camera';
import { Geolocation } from '@capacitor/geolocation';
import { Haptics, NotificationType } from '@capacitor/haptics';
import { firstValueFrom } from 'rxjs';

const API = 'https://api.example.com/v1';

@Injectable({ providedIn: 'root' })
export class HikeService {
  private readonly http = inject(HttpClient);

  async logHike(trailId: string, notes: string): Promise<void> {
    const photo = await Camera.getPhoto({
      quality: 80,
      resultType: CameraResultType.Uri,
      source: CameraSource.Camera,
    });
    const position = await Geolocation.getCurrentPosition({ enableHighAccuracy: true });

    const body = new FormData();
    body.append('hikedAt', new Date().toISOString());
    body.append('notes', notes);
    body.append('latitude', String(position.coords.latitude));
    body.append('longitude', String(position.coords.longitude));
    if (photo.webPath) {
      const blob = await (await fetch(photo.webPath)).blob();
      body.append('photo', blob, 'hike.jpg');
    }

    await firstValueFrom(this.http.post(`${API}/trails/${trailId}/hikes`, body));
    await Haptics.notification({ type: NotificationType.Success });
  }
}

Camera.getPhoto rejects when the user cancels the camera, so a real implementation distinguishes cancellation from failure before showing an error. The page checks the location permission with ensureLocationPermission before calling logHike. On the web, the same code runs using a file picker and the browser geolocation prompt, which makes the page testable with ionic serve.