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);
};
Example: Get Image from Gallery
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 '@capacitor/device';
const getInfo = async () => {
const info = await Device.getInfo();
console.log('Device Model:', info.model);
console.log('Platform:', info.platform);
console.log('UUID:', info.uuid);
};
getInfo();
Example: Check Battery Status
import { Device } from '@capacitor/device';
const checkBattery = async () => {
const isLowPower = await Device.isLowPowerMode();
console.log('Low Power Mode:', 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 '@capacitor/network';
const checkNetwork = async () => {
const status = await Network.getStatus();
console.log('Network type:', status.connectionType);
console.log('Is online:', status.connected);
};
checkNetwork();
Example: Listen for Network Changes
import { Network } from '@capacitor/network';
Network.addListener('networkStatusChange', (status) => {
console.log('Network status changed:', status);
});
// Listen for connection
Network.addListener('networkConnect', (status) => {
console.log('Connected to network:', status);
});
// Listen for disconnection
Network.addListener('networkDisconnect', () => {
console.log('Disconnected from network');
});
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 | |
| Storage.get() | Retrieves a value by key | |
| Storage.remove() | Removes a key-value pair | |
| Storage.clear() | Clears all stored data | |
| Storage.keys() | Lists all stored 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 | |
| impactMedium() | Triggers a medium impact feedback | |
| impactHeavy() | Triggers a heavy impact feedback | |
| notificationSuccess() | Triggers a success notification feedback | |
| notificationWarning() | Triggers a warning notification feedback | |
| notificationError() | Triggers an error notification feedback | |
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 | |
| Clipboard.read() | Reads text from the system clipboard | |
Note: The Clipboard API is supported on iOS, Android, and Web platforms.