### Clone and Setup Capacitor CLI for Local Development Source: https://github.com/ionic-team/capacitor/blob/main/cli/README.md Clone the Capacitor repository, navigate to the CLI directory, and install its dependencies. This is for contributing to or testing local changes to the CLI. ```bash git clone https://github.com/ionic-team/capacitor.git cd cli npm install ``` -------------------------------- ### Start a New Ionic App with Capacitor Source: https://github.com/ionic-team/capacitor/blob/main/README.md Install the Ionic CLI globally and use it to start a new app project configured with Capacitor. This is recommended for new projects. ```bash npm install -g @ionic/cli ionic start --capacitor ``` -------------------------------- ### CapacitorHttp GET Request Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Demonstrates how to perform an HTTP GET request using Capacitor's Http plugin. Ensure the plugin is installed and configured. ```typescript import { CapacitorHttp } from '@capacitor/core'; const url = 'https://api.example.com/data'; const options = { params: { id: '123', sort: 'asc' } }; CapacitorHttp.get({ url, ...options }) .then(({ data }) => { console.log('Data received:', data); }) .catch((error) => { console.error('HTTP Error:', error); }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/ionic-team/capacitor/blob/main/CONTRIBUTING.md Installs project dependencies using npm. This is a required step for local development setup. ```shell npm install ``` -------------------------------- ### Install Capacitor Core and CLI Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Install the necessary Capacitor packages using npm and initialize a new Capacitor project. ```bash npm install @capacitor/core @capacitor/cli npx capacitor init ``` -------------------------------- ### HttpOptions Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/types.md Example demonstrating how to configure HttpOptions for a POST request, including URL, method, headers, data, and timeouts. ```typescript const options: HttpOptions = { url: 'https://api.example.com/users', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token', }, data: { name: 'John', email: 'john@example.com' }, responseType: 'json', connectTimeout: 5000, readTimeout: 10000, }; ``` -------------------------------- ### Configure Custom App Start Path Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/configuration.md Define a specific HTML file to load when the application starts, instead of the default `/index.html`. ```json { "server": { "appStartPath": "login.html" } } ``` -------------------------------- ### Check Project Setup Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Verifies project setup for common issues and provides suggestions for fixes. Can check a specific platform or the entire project. ```bash capacitor doctor capacitor doctor android capacitor doctor ios ``` -------------------------------- ### Install Capacitor CLI Locally Source: https://github.com/ionic-team/capacitor/blob/main/cli/README.md Install the Capacitor CLI as a development dependency in your project. This is the recommended installation method. ```bash npm install @capacitor/cli --save-dev ``` -------------------------------- ### Example capacitor.config.json Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/configuration.md A comprehensive example of a capacitor.config.json file, demonstrating common settings like appId, appName, webDir, server configuration, and plugin enablement. ```json { "appId": "com.example.myapp", "appName": "My App", "webDir": "dist", "server": { "hostname": "localhost", "iosScheme": "capacitor" }, "plugins": { "CapacitorHttp": { "enabled": true } } } ``` -------------------------------- ### Install Capacitor CLI Globally Source: https://github.com/ionic-team/capacitor/blob/main/cli/README.md Install the Capacitor CLI globally. This method is not recommended for project development. ```bash npm install -g @capacitor/cli ``` -------------------------------- ### Install Capacitor CLI Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Installs the Capacitor CLI globally or as a development dependency. ```bash npm install -g @capacitor/cli # or npm install --save-dev @capacitor/cli ``` -------------------------------- ### Complete Capacitor Configuration Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/configuration.md A comprehensive example showing various configuration options for Capacitor, including app settings, server, platform-specific settings, plugins, and Cordova. ```json { "appId": "com.example.myapp", "appName": "My App", "webDir": "dist", "loggingBehavior": "debug", "backgroundColor": "#ffffff", "zoomEnabled": false, "initialFocus": true, "server": { "hostname": "localhost", "iosScheme": "capacitor", "androidScheme": "https", "allowNavigation": ["https://example.com"] }, "android": { "path": "android", "allowMixedContent": false, "webContentsDebuggingEnabled": false, "minWebViewVersion": 60, "flavor": "production", "buildOptions": { "releaseType": "AAB", "signingType": "apksigner" } }, "ios": { "path": "ios", "scheme": "App", "contentInset": "never", "scrollEnabled": true, "limitsNavigationsToAppBoundDomains": false, "preferredContentMode": "recommended", "handleApplicationNotifications": true, "buildOptions": { "signingStyle": "automatic", "exportMethod": "app-store-connect" } }, "plugins": { "CapacitorHttp": { "enabled": false }, "CapacitorCookies": { "enabled": false }, "SystemBars": { "style": "DEFAULT", "hidden": false }, "MyCustomPlugin": { "apiKey": "value" } }, "cordova": { "preferences": { "ScrollEnabled": "false" } } } ``` -------------------------------- ### GeolocationPlugin Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/web-plugin.md An example implementation of a Geolocation web plugin, demonstrating how to get the current location and watch for location updates. ```APIDOC ## Example: Full Plugin Implementation ```typescript import { WebPlugin, PluginListenerHandle } from '@capacitor/core'; interface LocationData { latitude: number; longitude: number; accuracy: number; } class GeolocationPlugin extends WebPlugin { private watchId: number | null = null; constructor() { super(); // Map window 'deviceorientation' event to 'orientationChanged' plugin event this.registerWindowListener('deviceorientation', 'orientationChanged'); } async getCurrentLocation(): Promise { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( (position) => { resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, }); }, (error) => reject(new Error(error.message)) ); }); } async startWatchingLocation(): Promise { return new Promise((resolve, reject) => { this.watchId = navigator.geolocation.watchPosition( (position) => { const data: LocationData = { latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, }; this.notifyListeners('locationUpdated', data); }, (error) => reject(new Error(error.message)) ); resolve({ remove: async () => { if (this.watchId !== null) { navigator.geolocation.clearWatch(this.watchId); } }, }); }); } } export const GeolocationPluginWeb = new GeolocationPlugin(); ``` ``` -------------------------------- ### Build Capacitor CLI Source: https://github.com/ionic-team/capacitor/blob/main/cli/README.md Build the Capacitor CLI after cloning and installing dependencies. This step is part of the local development setup. ```bash npm run build ``` -------------------------------- ### Example HttpParams Usage Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/types.md Illustrates creating HttpParams, including an example with an array for a parameter that can have multiple values, showing the resulting URL query string. ```typescript const params: HttpParams = { userId: '123', filter: 'active', tags: ['javascript', 'web'], // Arrays are supported }; // Resulting URL: ?userId=123&filter=active&tags=javascript&tags=web ``` -------------------------------- ### Initial Project Setup with Capacitor Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Commands to create a new Capacitor project or initialize an existing web project, followed by adding platforms and running on a device. ```bash # Create new project with Ionic Framework ionic start myapp --capacitor # Or initialize existing web project npm install @capacitor/core @capacitor/cli npx capacitor init # Add platforms npx capacitor add android npx capacitor add ios # Run on device npx capacitor run android npx capacitor run ios ``` -------------------------------- ### Initialize Capacitor in an App Source: https://github.com/ionic-team/capacitor/blob/main/README.md Install Capacitor core and CLI packages, then initialize Capacitor in your project. This sets up the necessary configuration for Capacitor. ```bash npm install @capacitor/core @capacitor/cli npx cap init ``` -------------------------------- ### Configure a Capacitor Plugin Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Example of how to configure a plugin using the capacitor.config.json file. ```json { "plugins": { "MyPlugin": { "option1": "value1", "option2": true } } } ``` -------------------------------- ### Example HttpHeaders Usage Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/types.md Demonstrates how to create an HttpHeaders object with common headers like Content-Type, Authorization, and custom headers. ```typescript const headers: HttpHeaders = { 'Content-Type': 'application/json', 'Authorization': 'Bearer eyJhbGc...', 'X-Custom-Header': 'value', }; ``` -------------------------------- ### WebPlugin Base Class Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Illustrates how to create a web plugin implementation, including event listener management and emitting notifications. ```typescript import { WebPlugin, Capacitor } from '@capacitor/core'; import type { MyPlugin, MyPluginListener } from './definitions'; export class MyWebPlugin extends WebPlugin implements MyPlugin { async echo(options: { value: string }): Promise<{ value: string }> { console.log('ECHO', options); return options; } async addListenerForEvent(options: { callbackId: string }): Promise { const listener = await super.addListener('myEvent', (data) => { Capacitor.getListeners('myEvent').forEach(listener => { if (listener.callbackId === options.callbackId) { listener.callback(data); } }); }); return listener; } removeListeners(): Promise { return super.removeAllListeners(); } notifyListeners(eventName: string, data: any): Promise { return super.notifyListeners(eventName, data); } hasListeners(eventName: string): Promise { return super.hasListeners(eventName); } } const MyPlugin = new MyWebPlugin(); export { MyPlugin }; import { registerWebPlugin } from '@capacitor/core'; registerWebPlugin(MyPlugin); ``` -------------------------------- ### SystemBars Set Status Bar Style Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Shows how to change the status bar style (e.g., light or dark content) using the SystemBars plugin. Ensure the plugin is installed. ```typescript import { SystemBars, SystemBarsStyle } from '@capacitor/core'; SystemBars.setStyle({ style: SystemBarsStyle.Light }) .then(() => { console.log('Status bar style set to light.'); }) .catch((error) => { console.error('SystemBars Error:', error); }); ``` -------------------------------- ### Perform a GET Request with CapacitorHttp Source: https://github.com/ionic-team/capacitor/blob/main/core/http.md Example of making a GET request using CapacitorHttp. Options include URL, headers, and parameters. The response is of type HttpResponse. ```typescript import { CapacitorHttp } from '@capacitor/core'; // Example of a GET request const doGet = () => { const options = { url: 'https://example.com/my/api', headers: { 'X-Fake-Header': 'Fake-Value' }, params: { size: 'XL' }, }; const response: HttpResponse = await CapacitorHttp.get(options); // or... // const response = await CapacitorHttp.request({ ...options, method: 'GET' }) }; ``` -------------------------------- ### Install SwiftLint Source: https://github.com/ionic-team/capacitor/blob/main/CONTRIBUTING.md Installs SwiftLint using Homebrew for macOS users. This tool helps maintain code quality for iOS contributions. ```shell brew install swiftlint ``` -------------------------------- ### Capacitor Configuration File (JSON) Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Example of the primary capacitor.config.json file used for project configuration. ```json { "appId": "com.example.app", "appName": "My App", "webDir": "dist", "server": { "hostname": "localhost" }, "plugins": { "CapacitorHttp": { "enabled": false } } } ``` -------------------------------- ### List Installed Plugins Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Displays all installed Cordova and Capacitor plugins, optionally filtered by platform. Useful for auditing project dependencies. ```bash capacitor ls capacitor ls android capacitor ls ios ``` -------------------------------- ### Remove Plugin Listener Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/types.md Example demonstrating how to add a listener and then remove it using the PluginListenerHandle. ```typescript const handle = await plugin.addListener('event', () => {}); await handle.remove(); // Remove the listener ``` -------------------------------- ### Full Geolocation Web Plugin Implementation Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/web-plugin.md Example of a complete Geolocation web plugin demonstrating `getCurrentLocation` and `startWatchingLocation`. ```typescript import { WebPlugin, PluginListenerHandle } from '@capacitor/core'; interface LocationData { latitude: number; longitude: number; accuracy: number; } class GeolocationPlugin extends WebPlugin { private watchId: number | null = null; constructor() { super(); // Map window 'deviceorientation' event to 'orientationChanged' plugin event this.registerWindowListener('deviceorientation', 'orientationChanged'); } async getCurrentLocation(): Promise { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( (position) => { resolve({ latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, }); }, (error) => reject(new Error(error.message)) ); }); } async startWatchingLocation(): Promise { return new Promise((resolve, reject) => { this.watchId = navigator.geolocation.watchPosition( (position) => { const data: LocationData = { latitude: position.coords.latitude, longitude: position.coords.longitude, accuracy: position.coords.accuracy, }; this.notifyListeners('locationUpdated', data); }, (error) => reject(new Error(error.message)) ); resolve({ remove: async () => { if (this.watchId !== null) { navigator.geolocation.clearWatch(this.watchId); } }, }); }); } } export const GeolocationPluginWeb = new GeolocationPlugin(); ``` -------------------------------- ### Use Plugin in Application Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/plugin-development.md Example of how to import and use the custom plugin within an application, including calling methods and listening for events. ```typescript import { MyPlugin } from 'my-plugin'; // Call web method const result = await MyPlugin.echo({ value: 'Hello' }); console.log(result.value); // 'Hello' // Get device info const info = await MyPlugin.getDeviceInfo(); console.log(info.platform); // 'android', 'ios', or 'web' // Listen for events const handle = await MyPlugin.addListener('appPause', (data) => { console.log('App paused at:', data.timestamp); }); // Remove listener await handle.remove(); ``` -------------------------------- ### Capacitor CLI Verbose Logging and Configuration Override Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Examples demonstrating how to enable verbose logging for the Capacitor CLI and override configuration options using environment variables. ```bash DEBUG=capacitor:* npx capacitor sync CAP_APP_WEBDIR=dist npx capacitor sync ``` -------------------------------- ### Capacitor API Usage Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Demonstrates how to import and use core Capacitor functionalities like checking the platform, making HTTP requests, managing cookies, controlling system bars, and registering custom plugins. ```typescript import { Capacitor, registerPlugin } from '@capacitor/core'; // Check platform const platform = Capacitor.getPlatform(); console.log(`Running on ${platform}`); // Use built-in plugins import { CapacitorHttp, CapacitorCookies, SystemBars } from '@capacitor/core'; // Make HTTP request const response = await CapacitorHttp.get({ url: 'https://api.example.com' }); // Manage cookies const cookies = await CapacitorCookies.getCookies(); // Control system bars await SystemBars.setStyle({ style: 'DARK' }); // Register custom plugin const MyPlugin = registerPlugin('MyPlugin', { web: () => import('./web').then(m => m.MyPluginWeb), }); ``` -------------------------------- ### WebView Set Server Asset Path Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Configures the base path for server assets in the WebView using the WebView plugin. This is useful for custom URL schemes. ```typescript import { WebView } from '@capacitor/core'; WebView.setServerAssetPath({ path: '/myassets' }) .then(() => { console.log('Server asset path set.'); }) .catch((error) => { console.error('WebView Error:', error); }); ``` -------------------------------- ### GET Request with Basic URL Parameters Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Sends a GET request with basic key-value URL parameters. The plugin automatically formats the URL. ```typescript const response = await CapacitorHttp.get({ url: 'https://api.example.com/users', params: { page: '1', limit: '10', sort: 'name', }, }); // Resulting URL: https://api.example.com/users?page=1&limit=10&sort=name ``` -------------------------------- ### Initial Focus Configuration Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/configuration.md Controls whether the WebView should receive focus when the application starts. Defaults to true. ```json { "initialFocus": true } ``` -------------------------------- ### Open Native Project in IDE Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Opens the native project in its respective IDE (Android Studio for Android, Xcode for iOS). Platform IDEs must be installed. ```bash capacitor open capacitor open android # Opens Android Studio capacitor open ios # Opens Xcode ``` -------------------------------- ### GET Request with Authorization Headers Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Demonstrates setting various authorization headers, including Bearer Token, Basic Auth, and custom API keys. ```typescript // Bearer Token await CapacitorHttp.get({ url: 'https://api.example.com/protected', headers: { 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', }, }); // Basic Auth const credentials = btoa('username:password'); await CapacitorHttp.get({ url: 'https://api.example.com/protected', headers: { 'Authorization': `Basic ${credentials}`, }, }); // Custom Auth await CapacitorHttp.get({ url: 'https://api.example.com/protected', headers: { 'X-API-Key': 'secret-key-12345', }, }); ``` -------------------------------- ### CapacitorHttp POST Request Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Shows how to send an HTTP POST request with JSON data using Capacitor's Http plugin. Configure headers and body as needed. ```typescript import { CapacitorHttp } from '@capacitor/core'; const url = 'https://api.example.com/submit'; const data = { name: 'Example User', email: 'user@example.com' }; const options = { headers: { 'Content-Type': 'application/json' }, data: data }; CapacitorHttp.post({ url, ...options }) .then(({ data }) => { console.log('Response:', data); }) .catch((error) => { console.error('HTTP Error:', error); }); ``` -------------------------------- ### Migrate Capacitor Version Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Guides through migrating your app to a new major version of Capacitor. Can skip prompts or specify a package manager. ```bash capacitor migrate capacitor migrate --noprompt capacitor migrate --packagemanager pnpm ``` -------------------------------- ### Server URL Configuration Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/configuration.md Load an external URL in the WebView, useful for live-reloading during development. Not intended for production. Example shows an IP address and port. ```json { "server": { "url": "http://192.168.1.100:3000" } } ``` -------------------------------- ### Add Native Platforms to Capacitor Project Source: https://github.com/ionic-team/capacitor/blob/main/README.md Install the desired native platform packages (e.g., Android, iOS) and add them to your Capacitor project. This prepares your project for native builds. ```bash npm install @capacitor/android npx cap add android npm install @capacitor/ios npx cap add ios ``` -------------------------------- ### Unit Test Example for Web Plugin Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/plugin-development.md Write unit tests for your web plugin using a testing framework like Jest. Mock plugin methods and assert expected return values and behavior. ```typescript // test/web.spec.ts import { MyPluginWeb } from '../src/web'; describe('MyPluginWeb', () => { let plugin: MyPluginWeb; beforeEach(() => { plugin = new MyPluginWeb(); }); test('echo returns the input value', async () => { const result = await plugin.echo({ value: 'test' }); expect(result.value).toBe('test'); }); test('getDeviceInfo returns web platform', async () => { const info = await plugin.getDeviceInfo(); expect(info.platform).toBe('web'); }); }); ``` -------------------------------- ### CapacitorCookies Get Cookie Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Illustrates how to retrieve a specific cookie by its name using Capacitor's Cookies plugin. The cookie's value will be returned. ```typescript import { CapacitorCookies } from '@capacitor/core'; CapacitorCookies.getCookie({ name: 'session_id' }) .then(({ value }) => { console.log('Session ID:', value); }) .catch((error) => { console.error('Cookie Error:', error); }); ``` -------------------------------- ### CapacitorCookies Set Cookie Example Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Demonstrates how to set a cookie using Capacitor's Cookies plugin. Specify domain, path, and expiration as required. ```typescript import { CapacitorCookies } from '@capacitor/core'; const options = { name: 'session_id', value: 'abc123xyz', domain: 'example.com', path: '/', expires: '2024-12-31T23:59:59Z' }; CapacitorCookies.setCookie(options) .then(() => { console.log('Cookie set successfully.'); }) .catch((error) => { console.error('Cookie Error:', error); }); ``` -------------------------------- ### Make a POST HTTP Request Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Use the `request` method for full control over HTTP requests, including method, headers, body, and timeouts. This example demonstrates a POST request with JSON data. ```typescript import { CapacitorHttp } from '@capacitor/core'; const response = await CapacitorHttp.request({ url: 'https://api.example.com/data', method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer token123', }, data: { name: 'John', age: 30, }, connectTimeout: 5000, readTimeout: 10000, responseType: 'json', }); console.log(response.status); // 200 console.log(response.data); // { id: 1, name: 'John', age: 30 } console.log(response.headers); // { 'content-type': 'application/json', ... } ``` -------------------------------- ### Perform a POST Request with CapacitorHttp Source: https://github.com/ionic-team/capacitor/blob/main/core/http.md Example of making a POST request using CapacitorHttp. Data can be passed as a raw JS Object. Options include URL, headers, and data. ```typescript import { CapacitorHttp } from '@capacitor/core'; // Example of a POST request. Note: data // can be passed as a raw JS Object (must be JSON serializable) const doPost = () => { const options = { url: 'https://example.com/my/api', headers: { 'X-Fake-Header': 'Fake-Value' }, data: { foo: 'bar' }, }; const response: HttpResponse = await CapacitorHttp.post(options); // or... // const response = await CapacitorHttp.request({ ...options, method: 'POST' }) }; ``` -------------------------------- ### Make a GET HTTP Request Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Use the `get` method for making HTTP GET requests. The method is automatically set to 'GET'. ```typescript import { CapacitorHttp } from '@capacitor/core'; const response = await CapacitorHttp.get({ url: 'https://api.example.com/users/123', headers: { 'Authorization': 'Bearer token', }, }); console.log(response.data); ``` -------------------------------- ### Building for Release Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Commands to build web assets, sync them to native projects, and then build release versions for iOS and Android. ```bash # Build web assets npm run build # Copy to native projects npx capacitor sync # Build iOS release npx capacitor build ios --xcode-team-id ABC123 # Build Android release npx capacitor build android --keystorepath /path/to/keystore.jks --androidreleasetype AAB ``` -------------------------------- ### CapacitorHttp.get Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Makes an HTTP GET request to the specified URL with optional headers. The method is automatically set to 'GET'. ```APIDOC ## CapacitorHttp.get ### Description Makes an HTTP GET request to the specified URL with optional headers. The method is automatically set to 'GET'. ### Method `get(options: HttpOptions): Promise` ### Parameters #### Request Body (`HttpOptions`) - **url** (string) - Required - The URL to fetch. - **headers** (object) - Optional - An object containing the request headers. - **responseType** (string) - Optional - The type of the response body ('json', 'text'). ### Request Example ```typescript const response = await CapacitorHttp.get({ url: 'https://api.example.com/users/123', headers: { 'Authorization': 'Bearer token', }, }); console.log(response.data); ``` ### Response #### Success Response (`HttpResponse`) - **status** (number) - The HTTP status code of the response. - **data** (any) - The response body. - **headers** (object) - An object containing the response headers. #### Response Example ```json { "status": 200, "data": { "id": 123, "name": "Example User" }, "headers": { "content-type": "application/json" } } ``` ``` -------------------------------- ### CapacitorHttp.get Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/core-plugins.md Makes an HTTP GET request. It takes HttpOptions (where method is set to 'GET') and returns a Promise resolving to HttpResponse. ```APIDOC ## CapacitorHttp.get(options) ### Description Make an HTTP GET request. ### Method GET ### Endpoint /get ### Parameters #### Request Body - **options** (HttpOptions) - Required - HTTP request configuration (method will be set to 'GET') ### Request Example ```json { "url": "https://api.example.com/users/123" } ``` ### Response #### Success Response (200) - **data** (any) - The response body. #### Response Example ```json { "data": "User data" } ``` ``` -------------------------------- ### Initialize Capacitor Project Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Initializes a new Capacitor project with a specified app name and ID. Optionally configures the web directory or skips app ID validation. ```bash capacitor init [appName] [appId] ``` ```bash capacitor init "My App" "com.example.myapp" ``` ```bash capacitor init "My App" "com.example.myapp" --web-dir dist ``` ```bash capacitor init "My App" "com.example.myapp" --skip-appid-validation ``` -------------------------------- ### GET Request with Array URL Parameters Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Sends a GET request with array parameters, where each array element is appended as a separate parameter. ```typescript const response = await CapacitorHttp.get({ url: 'https://api.example.com/users', params: { ids: ['1', '2', '3'], tags: ['javascript', 'web'], }, }); // Resulting URL: https://api.example.com/users?ids=1&ids=2&ids=3&tags=javascript&tags=web ``` -------------------------------- ### Make HTTP GET Request with CapacitorHttp Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/core-plugins.md Use CapacitorHttp.get for simple HTTP GET requests. Provide the URL to fetch data from. ```typescript const response = await CapacitorHttp.get({ url: 'https://api.example.com/users/123', }); console.log(response.data); ``` -------------------------------- ### Run Capacitor Application Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Builds and deploys the application to a device or emulator. If no platform is specified, it interactively lists available targets. Use options to configure build and deployment. ```bash capacitor run capacitor run android capacitor run ios --scheme MyScheme capacitor run android --no-sync capacitor run ios --live-reload --host 192.168.1.100 --port 8100 ``` -------------------------------- ### buildRequestInit Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/core-plugins.md Builds a `RequestInit` object for use with `fetch()` based on HTTP options provided. ```APIDOC ## buildRequestInit ### Description Builds a `RequestInit` object for use with `fetch()` based on HTTP options. ### Method Signature ```typescript buildRequestInit(options: HttpOptions, extra?: RequestInit): RequestInit ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (HttpOptions) - Required - HTTP request options. - **extra** (RequestInit) - Optional - Additional fetch options to merge. ### Returns A `RequestInit` object ready for `fetch()`. ### Example ```typescript import { buildRequestInit } from '@capacitor/core'; const init = buildRequestInit({ url: 'https://api.example.com/data', method: 'POST', data: { name: 'John' }, headers: { 'Content-Type': 'application/json' }, }); const response = await fetch('https://api.example.com/data', init); ``` ``` -------------------------------- ### show Source: https://github.com/ionic-team/capacitor/blob/main/core/system-bars.md Shows the system bars. This method can optionally take an options object to specify which bar to show. ```APIDOC ## show ### Description Shows the system bars. ### Method `show(options?: SystemBarsVisibilityOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **`options`** (SystemBarsVisibilityOptions) - Optional - An object specifying which bar to show. - **`bar`** (SystemBarType) - Optional - The system bar to show. Defaults to null. - **`animation`** (SystemBarsAnimation) - Optional - The type of animation used when showing. Only supported on iOS. Defaults to 'FADE'. ### Request Example ```json { "bar": "NAVIGATION_BAR", "animation": "NONE" } ``` ### Response #### Success Response (void) This method returns a Promise that resolves with no value upon successful execution. #### Response Example (No response body for success) ``` -------------------------------- ### WebPlugin Implementation: Basic Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/plugin-development.md A basic implementation of a WebPlugin, demonstrating a simple method that echoes input. ```typescript import { WebPlugin } from '@capacitor/core'; export class MyPluginWeb extends WebPlugin { async echo(options: { value: string }) { return { value: options.value }; } } ``` -------------------------------- ### Make a GET Request with CapacitorHttp Source: https://github.com/ionic-team/capacitor/blob/main/core/http.md Make a specific HTTP GET request to a server using native libraries with CapacitorHttp. Accepts HttpOptions and returns a Promise of HttpResponse. ```typescript get(options: HttpOptions) => Promise ``` -------------------------------- ### Build Android Release Binaries Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Creates release binaries for Android. Use --flavor for specific build variants and --androidreleasetype for AAB or APK. Requires keystore configuration for signing. ```bash capacitor build android capacitor build android --flavor=production capacitor build android --androidreleasetype AAB --keystorepath /path/to/keystore.jks ``` -------------------------------- ### Run Android App on Device Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Build and deploy the Android application to a connected device or emulator. ```bash npx capacitor run android ``` -------------------------------- ### GET Request Disabling Redirects Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Sends a GET request and explicitly disables automatic redirection following. The response status will indicate the redirect code (e.g., 301, 302). ```typescript const response = await CapacitorHttp.get({ url: 'https://example.com/old-page', disableRedirects: true, }); // response.status will be 301/302 without following redirect ``` -------------------------------- ### Run iOS App on Device Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Build and deploy the iOS application to a connected device or simulator. ```bash npx capacitor run ios ``` -------------------------------- ### GET Request Allowing Redirects (Default) Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Performs a GET request that automatically follows HTTP redirects (301, 302, 307, 308). The final URL is returned in `response.url`. ```typescript // Follows HTTP redirects (301, 302, 307, 308) const response = await CapacitorHttp.get({ url: 'https://example.com/old-page', // Plugin automatically follows redirects }); // response.url will be the final URL ``` -------------------------------- ### WritableStream Methods Source: https://github.com/ionic-team/capacitor/blob/main/core/http.md Provides methods for interacting with WritableStream, including aborting the stream and getting a writer. ```APIDOC ## WritableStream This Streams API interface provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. ### Properties #### locked - **`locked`** (boolean) - Indicates if the stream is locked. ### Methods #### abort - **`abort`** - Aborts the stream with an optional reason. - Returns: `Promise` #### getWriter - **`getWriter`** - Returns a WritableStreamDefaultWriter to interact with the stream. - Returns: `WritableStreamDefaultWriter` ``` -------------------------------- ### Get All Cookies Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Retrieves all cookies. The returned object uses cookie names as keys and their values as values. ```typescript const allCookies = await CapacitorCookies.getCookies(); console.log(allCookies); // { sessionId: 'abc123', preferences: 'dark' } ``` -------------------------------- ### Capacitor CLI Usage Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Shows the basic usage of the Capacitor CLI and its alias. ```bash capacitor [command] [options] cap [command] [options] # Alias ``` -------------------------------- ### Set Web Directory via Environment Variable Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/configuration.md Configure the web directory using the CAP_APP_WEBDIR environment variable. ```bash # Set web directory export CAP_APP_WEBDIR=dist ``` -------------------------------- ### Get Document Response (Web Only) Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Fetches data as an HTML Document. This feature is only available on the web platform. ```typescript const response = await CapacitorHttp.get({ url: 'https://api.example.com/page.html', responseType: 'document', }); console.log(response.data instanceof Document); // true (web only) ``` -------------------------------- ### Sync Web App to Native Platform Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Runs both `copy` and `update` commands for a specified platform. Supports a deployment option for iOS. ```bash capacitor sync [platform] ``` ```bash capacitor sync ``` ```bash capacitor sync android ``` ```bash capacitor sync ios --deployment ``` -------------------------------- ### Get Blob or ArrayBuffer Response Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Fetches data as a Blob or ArrayBuffer. On Android/iOS, the response data is base64-encoded. ```typescript const response = await CapacitorHttp.get({ url: 'https://api.example.com/image.png', responseType: 'blob', // or 'arraybuffer' }); // response.data is base64-encoded on Android/iOS const binaryString = atob(response.data); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } ``` -------------------------------- ### CapacitorHttp.get Source: https://github.com/ionic-team/capacitor/blob/main/core/http.md Makes a specific HTTP GET request to a server using native libraries. Ideal for retrieving data. ```APIDOC ## get(...) ### Description Make a Http GET Request to a server using native libraries. ### Method GET ### Endpoint Not specified, as this is an SDK method. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (HttpOptions) - Required - Configuration options for the HTTP GET request. ### Request Example ```typescript const options = { url: 'https://example.com/my/api', headers: { 'X-Fake-Header': 'Fake-Value' }, params: { size: 'XL' } }; const response = await CapacitorHttp.get(options); ``` ### Response #### Success Response (200) * **response** (HttpResponse) - The response from the server. #### Response Example ```json { "data": { "key": "value" }, "status": 200, "url": "https://example.com/my/api", "headers": { "Content-Type": "application/json" } } ``` ``` -------------------------------- ### Get Current Platform Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/capacitor-global.md Use getPlatform() to determine the current operating environment (e.g., 'android', 'ios', 'web'). ```typescript import { Capacitor } from '@capacitor/core'; const platform = Capacitor.getPlatform(); console.log(`Running on ${platform}`); ``` -------------------------------- ### Copy Web App to Native Directories Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Copies the built web application assets to the native platform's web directory. Supports an inline option for source maps. ```bash capacitor copy [platform] ``` ```bash capacitor copy ``` ```bash capacitor copy android ``` ```bash capacitor copy ios ``` ```bash capacitor copy --inline ``` -------------------------------- ### Build Release Binary for Platform Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/cli-commands.md Builds a release binary for Android or iOS. Supports various platform-specific options for signing, configuration, and export methods. ```bash capacitor build ``` -------------------------------- ### Add Android Platform Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Add the Android platform to your Capacitor project. ```bash npx capacitor add android ``` -------------------------------- ### Accessing Exception Data Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/errors.md Example demonstrating how to access the 'data' property of a Capacitor exception, which can contain platform-specific details. ```typescript try { const result = await CapacitorHttp.request({ url: 'https://api.example.com' }); } catch (error) { if (error instanceof Capacitor.Exception) { // error.data might contain: // { platform: 'android', apiLevel: 28, requiredLevel: 29 } console.log('Error details:', error.data); } } ``` -------------------------------- ### Get Cookies for Specific URL Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/http-cookies-details.md Retrieves cookies associated with a specific URL. This is useful for managing cookies on a per-domain basis. ```typescript const urlCookies = await CapacitorCookies.getCookies({ url: 'https://example.com', }); ``` -------------------------------- ### Build Request Init for Fetch API Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md A utility function to help construct the `RequestInit` object for the `fetch` API, ensuring compatibility with Capacitor's HTTP handling. ```typescript import { buildRequestInit } from '@capacitor/core'; const url = 'https://api.example.com/data'; const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) }; const requestInit = buildRequestInit(options); fetch(url, requestInit) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Fetch Error:', error)); ``` -------------------------------- ### Handle Unimplemented Exception Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/errors.md Example of catching an 'UNIMPLEMENTED' exception. This occurs when a plugin method is called on a platform without an implementation. ```typescript import { ExceptionCode } from '@capacitor/core'; try { await SomeNativePlugin.nativeFeature(); } catch (error) { if (error.code === ExceptionCode.Unimplemented) { console.log('This feature is not available on your platform'); } } ``` -------------------------------- ### Add iOS Platform Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Add the iOS platform to your Capacitor project. ```bash npx capacitor add ios ``` -------------------------------- ### Handle Capacitor Exceptions Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/errors.md Example of how to catch and inspect Capacitor exceptions. It checks if an error is an instance of Capacitor.Exception and logs its properties. ```typescript import { Capacitor, ExceptionCode } from '@capacitor/core'; try { const result = await SomePlugin.someMethod(); } catch (error) { if (error instanceof Capacitor.Exception) { console.error(`Code: ${error.code}`); console.error(`Message: ${error.message}`); console.error(`Details:`, error.data); } } ``` -------------------------------- ### RequestInit Options Source: https://github.com/ionic-team/capacitor/blob/main/core/http.md The RequestInit interface provides a set of options that can be used to configure HTTP requests. These options control aspects like the request body, caching behavior, credentials, headers, and more. ```APIDOC ## RequestInit ### Description An object literal that can be used to specify initialization options for a Request object. ### Properties #### `body` - **Type**: `BodyInit` | `null` - **Description**: A `BodyInit` object or null to set request's body. #### `cache` - **Type**: `RequestCache` - **Description**: A string indicating how the request will interact with the browser's cache to set request's cache. #### `credentials` - **Type**: `RequestCredentials` - **Description**: A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. #### `headers` - **Type**: `HeadersInit` - **Description**: A `Headers` object, an object literal, or an array of two-item arrays to set request's headers. #### `integrity` - **Type**: `string` - **Description**: A cryptographic hash of the resource to be fetched by request. Sets request's integrity. #### `keepalive` - **Type**: `boolean` - **Description**: A boolean to set request's keepalive. #### `method` - **Type**: `string` - **Description**: A string to set request's method. #### `mode` - **Type**: `RequestMode` - **Description**: A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. #### `redirect` - **Type**: `RequestRedirect` - **Description**: A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. #### `referrer` - **Type**: `string` - **Description**: A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. #### `referrerPolicy` - **Type**: `ReferrerPolicy` - **Description**: A referrer policy to set request's referrerPolicy. #### `signal` - **Type**: `AbortSignal` - **Description**: An `AbortSignal` to set request's signal. #### `window` - **Type**: `any` - **Description**: Can only be null. Used to disassociate request from any Window. ``` -------------------------------- ### CapacitorCookies Plugin Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/INDEX.md Reference for the `CapacitorCookies` plugin, detailing methods for managing cookies, including setting, getting, deleting, and clearing cookies. ```APIDOC ## CapacitorCookies Plugin ### Description Manages cookies for the application. ### Methods - **`getCookies()`** - Get all cookies. - **`getCookie(name)`** - Get a specific cookie by name. - **`setCookie(options)`** - Set a cookie. - **`deleteCookie(options)`** - Delete a specific cookie. - **`clearCookies()`** - Clear all cookies for the current domain. - **`clearAllCookies()`** - Clear all cookies across all domains. ### Cookie Options - **`name`** (string) - Required - The name of the cookie. - **`value`** (string) - Required - The value of the cookie. - **`domain`** (string) - Optional - The domain for the cookie. - **`path`** (string) - Optional - The path for the cookie. - **`expires`** (string | Date) - Optional - Expiration date/time. - **`secure`** (boolean) - Optional - Whether the cookie should only be sent over HTTPS. - **`sameSite`** (string) - Optional - The SameSite attribute ('Strict', 'Lax', 'None'). ``` -------------------------------- ### Build RequestInit for Fetch Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/core-plugins.md Constructs a `RequestInit` object for use with `fetch()` based on provided HTTP options and optional extra fetch options. This is useful for making HTTP requests within Capacitor applications. ```typescript import { buildRequestInit } from '@capacitor/core'; const init = buildRequestInit({ url: 'https://api.example.com/data', method: 'POST', data: { name: 'John' }, headers: { 'Content-Type': 'application/json' }, }); const response = await fetch('https://api.example.com/data', init); ``` -------------------------------- ### Handle Unavailable Exception Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/errors.md Example of catching an 'UNAVAILABLE' exception. This occurs when an API is not available due to missing prerequisites or unsupported versions. ```typescript import { ExceptionCode } from '@capacitor/core'; try { const position = await Geolocation.getCurrentPosition(); } catch (error) { if (error.code === ExceptionCode.Unavailable) { console.log('Geolocation is not available in your browser'); } } ``` -------------------------------- ### CLI Commands Source: https://github.com/ionic-team/capacitor/blob/main/_autodocs/README.md Command-line interface tools for managing Capacitor projects. ```APIDOC ## CLI Commands ### Description Provides a set of command-line tools for initializing, building, running, and managing Capacitor projects across different platforms. ### Commands - **`init`** - Initializes a new Capacitor project. - **`add [platform]`** - Adds a specified platform (e.g., `android`, `ios`) to the project. - **`copy`** - Copies web assets to the native projects. - **`sync`** - Copies web assets and updates native projects. - **`update`** - Updates Capacitor dependencies. - **`build`** - Creates release binaries for the native projects. - **`run [platform]`** - Builds and deploys the app to a connected device or emulator for the specified platform. - **`open [platform]`** - Opens the native project in the corresponding IDE (e.g., Android Studio, Xcode). - **`ls`** - Lists installed Capacitor plugins. - **`doctor`** - Checks the project setup for potential issues. - **`config`** - Prints the current Capacitor configuration. - **`migrate`** - Migrates the project to a newer version of Capacitor. ```