Skip to main content

Using Capacitor Device Plugins

1. Using Camera Plugin

Property Description Values
camera Camera plugin for capturing images @capacitor/camera

Example: Capture Image

import { Camera, CameraResultType } from '@capacitor/camera';

const takePicture = async () => {
  const image = await Camera.getPhoto({
    quality: 90,
    allowEditing: true,
    resultType: CameraResultType.Uri
  });

  console.log(image.webPath);
};
import { Camera, CameraSource } from '@capacitor/camera';

const selectFromGallery = async () => {
  const image = await Camera.getPhoto({
    quality: 90,
    source: CameraSource.Photos,
    resultType: CameraResultType.Uri
  });

  console.log(image.webPath);
};
Note: Ensure that the camera plugin is properly configured in your capacitor.config.ts or capacitor.config.json.

2. Using Filesystem Plugin

Property Description Values
directory Directory to use for the filesystem operation DOCUMENTS, DATA, LIBRARY, TEMP
encoding Encoding to use for file operations UTF8, BASE64, ASCII
recursive Whether to perform recursive operations true, false

Example: Reading a file

import { Filesystem } from '@capacitor/filesystem';

const readFile = async () => {
  const result = await Filesystem.readFile({
    path: 'path/to/file.txt',
    directory: FilesystemDirectory.Documents,
    encoding: 'UTF8'
  });
  console.log(result.data);
};

Example: Writing a file

import { Filesystem } from '@capacitor/filesystem';

const writeFile = async () => {
  await Filesystem.writeFile({
    path: 'path/to/file.txt',
    data: 'Hello, Ionic!',
    directory: FilesystemDirectory.Documents,
    encoding: 'UTF8'
  });
};

Example: Getting file info

import { Filesystem } from '@capacitor/filesystem';

const getFileMetadata = async () => {
  const metadata = await Filesystem.stat({
    path: 'path/to/file.txt',
    directory: FilesystemDirectory.Documents
  });
  console.log(metadata.size);
};
Note: The Filesystem plugin requires appropriate permissions to be declared in the native app configuration files.

3. Using Geolocation Plugin

Property Description Default Notes
getCurrentPosition Gets the current geographic location of the device n/a
watchPosition Watches for changes in geographic location n/a
clearWatch Stops watching for location changes n/a

Example: Get Current Position

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

const getCurrentLocation = async () => {
  const position = await Geolocation.getCurrentPosition();
  console.log('Current location:', position.coords);
};

getCurrentLocation();

Example: Watch Position Changes

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

const watchPosition = async () => {
  const watchId = await Geolocation.watchPosition({}, (position, err) => {
    if (err) {
      console.error('Error watching position:', err);
      return;
    }
    console.log('Updated location:', position.coords);
  });

  // To stop watching:
  // Geolocation.clearWatch(watchId);
};

watchPosition();
Note: Ensure that the appropriate permissions are requested in your app's configuration files (e.g., AndroidManifest.xml or Info.plist) to access location services.

4. Using Device Plugin

Property Description Values Notes
Device.getInfo() Retrieves device information Promise<DeviceInfo> Returns device model, platform, UUID, etc.
Device.isBattery() Checks if battery info is available Promise<boolean> Useful for checking battery status support
Device.isLowPowerMode() Checks if device is in low power mode Promise<boolean> May be used to adjust app behavior

Example: Get Device Info

import { Device } from &#x27;@capacitor/device&#x27;;

const getInfo = async () => {
  const info = await Device.getInfo();
  console.log(&#x27;Device Model:&#x27;, info.model);
  console.log(&#x27;Platform:&#x27;, info.platform);
  console.log(&#x27;UUID:&#x27;, info.uuid);
};

getInfo();

Example: Check Battery Status

import { Device } from &#x27;@capacitor/device&#x27;;

const checkBattery = async () => {
  const isLowPower = await Device.isLowPowerMode();
  console.log(&#x27;Low Power Mode:&#x27;, isLowPower);
};

checkBattery();
Note: The Device plugin requires the @capacitor/device package to be installed.

5. Using Network Plugin

Property Description Values
Network.getStatus() Retrieves the current network status Promise<NetworkStatus>
Network.onConnect() Callback when device connects to network NetworkStatus
Network.onDisconnect() Callback when device disconnects from network void

Example: Check Network Status

import { Network } from &#x27;@capacitor/network&#x27;;

const checkNetwork = async () => {
  const status = await Network.getStatus();
  console.log(&#x27;Network type:&#x27;, status.connectionType);
  console.log(&#x27;Is online:&#x27;, status.connected);
};

checkNetwork();

Example: Listen for Network Changes

import { Network } from &#x27;@capacitor/network&#x27;;

Network.addListener(&#x27;networkStatusChange&#x27;, (status) => {
  console.log(&#x27;Network status changed:&#x27;, status);
});

// Listen for connection
Network.addListener(&#x27;networkConnect&#x27;, (status) => {
  console.log(&#x27;Connected to network:&#x27;, status);
});

// Listen for disconnection
Network.addListener(&#x27;networkDisconnect&#x27;, () => {
  console.log(&#x27;Disconnected from network&#x27;);
});
Note: The Network plugin requires the android.permission.ACCESS_NETWORK_STATE permission on Android.
Warning: On iOS, the plugin uses Reachability to detect network status. It may not always reflect real-time changes.
Property Description Notes
connectionType Current network type (e.g., cellular, wifi) 'cellular', 'wifi', 'none'
connected Whether device is connected to network true or false
downlink Estimated downlink bandwidth in Mbps NEW Available in Capacitor 5+
effectiveType Effective connection type (e.g., slow-2g, 3g) NEW Available in Capacitor 5+

6. Using Storage Plugin

Property Description Usage
Storage.set() Sets a key-value pair in storage
import { Plugins } from '@capacitor/core';

const { Storage } = Plugins;

await Storage.set({
  key: 'user',
  value: JSON.stringify({ name: 'John', age: 30 })
});
Storage.get() Retrieves a value by key
const { Storage } = Plugins;

const { value } = await Storage.get({ key: 'user' });
const user = JSON.parse(value);
Storage.remove() Removes a key-value pair
const { Storage } = Plugins;

await Storage.remove({ key: 'user' });
Storage.clear() Clears all stored data
const { Storage } = Plugins;

await Storage.clear();
Storage.keys() Lists all stored keys
const { Storage } = Plugins;

const { keys } = await Storage.keys();
Note: The Storage plugin uses the underlying platform’s storage mechanism (e.g., localStorage on web, SQLite on native platforms). Data is persisted across app sessions.

7. Using App Plugin

Property Description Values Notes
App.getInfo() Retrieves basic application information { name, id, version, build } Available on all platforms
App.getLaunchUrl() Gets the URL that was used to launch the app string Useful for deep linking and handling app launches from external sources
App.addListener('appUrlOpen', callback) Listen for app URL open events Event Triggers when the app is opened via a URL (e.g., from a deep link)
App.addListener('appRestoredResult', callback) Listen for restored app results Event Used to handle results from backgrounded app states

Example: Handling App URL Opens

import { App } from '@capacitor/app';

App.addListener('appUrlOpen', (event) => {
  console.log('App opened with URL:', event.url);
});

// Handle deep links or custom schemes
const handleDeepLink = (url: string) => {
  if (url.includes('myapp://')) {
    // Parse and navigate accordingly
  }
});

Example: Retrieving App Info

import { App } from '@capacitor/app';

const appInfo = await App.getInfo();
console.log('App Name:', appInfo.name);
console.log('Version:', appInfo.version);
Note: The App plugin is part of the Capacitor core plugins and provides access to native app lifecycle events and metadata.

8. Using Haptics Plugin

Property Description Usage
impactLight() Triggers a light impact feedback
import { Haptics } from '@capacitor/haptics';

Haptics.impactLight();
impactMedium() Triggers a medium impact feedback
import { Haptics } from '@capacitor/haptics';

Haptics.impactMedium();
impactHeavy() Triggers a heavy impact feedback
import { Haptics } from '@capacitor/haptics';

Haptics.impactHeavy();
notificationSuccess() Triggers a success notification feedback
import { Haptics } from '@capacitor/haptics';

Haptics.notificationSuccess();
notificationWarning() Triggers a warning notification feedback
import { Haptics } from '@capacitor/haptics';

Haptics.notificationWarning();
notificationError() Triggers an error notification feedback
import { Haptics } from '@capacitor/haptics';

Haptics.notificationError();
Note: Haptics feedback is only available on physical devices and will not work in a browser or simulator.

9. Using Keyboard Plugin

Property Description Values
keyboard.addListener Listen for keyboard events 'keyboardWillShow', 'keyboardWillHide'
keyboard.show Manually show the keyboard void
keyboard.hide Manually hide the keyboard void

Example: Listening to Keyboard Events

import { Keyboard } from '@capacitor/keyboard';

Keyboard.addListener('keyboardWillShow', (info) => {
  console.log('Keyboard height:', info.keyboardHeight);
});

Keyboard.addListener('keyboardWillHide', () => {
  console.log('Keyboard hidden');
});

Example: Showing and Hiding Keyboard

import { Keyboard } from '@capacitor/keyboard';

// Show keyboard
Keyboard.show();

// Hide keyboard
Keyboard.hide();
Note: The Keyboard plugin is only available on mobile platforms (iOS, Android). It does not work in web browsers.

10. Using Clipboard Plugin

Property Description Usage
Clipboard.write() Writes text to the system clipboard
import { Clipboard } from '@capacitor/clipboard';

Clipboard.write({
  string: 'Hello, Ionic!'
});
Clipboard.read() Reads text from the system clipboard
import { Clipboard } from '@capacitor/clipboard';

const { value } = await Clipboard.read();
Note: The Clipboard API is supported on iOS, Android, and Web platforms.

Was this article helpful?