Skip to content

Instantly share code, notes, and snippets.

@nikhilkh
Created August 30, 2015 16:42
Show Gist options
  • Save nikhilkh/1d11be5a2127154165bc to your computer and use it in GitHub Desktop.
Save nikhilkh/1d11be5a2127154165bc to your computer and use it in GitHub Desktop.
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*
- [cordova-plugin-battery-status](#cordova-plugin-battery-status)
- [Installation](#installation)
- [batterystatus](#batterystatus)
- [Supported Platforms](#supported-platforms)
- [Android and Amazon Fire OS Quirks](#android-and-amazon-fire-os-quirks)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks)
- [Windows Quirks](#windows-quirks)
- [Browser Quirks](#browser-quirks)
- [Example](#example)
- [batterycritical](#batterycritical)
- [Supported Platforms](#supported-platforms-1)
- [Windows Quirks](#windows-quirks-1)
- [Example](#example-1)
- [Browser Quirks](#browser-quirks-1)
- [batterylow](#batterylow)
- [Supported Platforms](#supported-platforms-2)
- [Windows Quirks](#windows-quirks-2)
- [Example](#example-2)
- [Browser Quirks](#browser-quirks-2)
- [cordova-plugin-camera](#cordova-plugin-camera)
- [Installation](#installation-1)
- [API](#api)
- [navigator.camera.getPicture](#navigatorcameragetpicture)
- [Description](#description)
- [Supported Platforms](#supported-platforms-3)
- [Example](#example-3)
- [Preferences (iOS)](#preferences-ios)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks)
- [Android Quirks](#android-quirks)
- [Browser Quirks](#browser-quirks-3)
- [Firefox OS Quirks](#firefox-os-quirks)
- [iOS Quirks](#ios-quirks)
- [Windows Phone 7 Quirks](#windows-phone-7-quirks)
- [Tizen Quirks](#tizen-quirks)
- [CameraOptions](#cameraoptions)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-1)
- [Android Quirks](#android-quirks-1)
- [BlackBerry 10 Quirks](#blackberry-10-quirks)
- [Firefox OS Quirks](#firefox-os-quirks-1)
- [iOS Quirks](#ios-quirks-1)
- [Tizen Quirks](#tizen-quirks-1)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-1)
- [CameraError](#cameraerror)
- [Description](#description-1)
- [cameraSuccess](#camerasuccess)
- [Description](#description-2)
- [Example](#example-4)
- [CameraPopoverHandle](#camerapopoverhandle)
- [Description](#description-3)
- [Supported Platforms](#supported-platforms-4)
- [Example](#example-5)
- [CameraPopoverOptions](#camerapopoveroptions)
- [Description](#description-4)
- [navigator.camera.cleanup](#navigatorcameracleanup)
- [Description](#description-5)
- [Supported Platforms](#supported-platforms-5)
- [Example](#example-6)
- [cordova-plugin-console](#cordova-plugin-console)
- [Installation](#installation-2)
- [Android Quirks](#android-quirks-2)
- [Supported Methods](#supported-methods)
- [Partially supported Methods](#partially-supported-methods)
- [Not supported Methods](#not-supported-methods)
- [Supported formatting](#supported-formatting)
- [cordova-plugin-contacts](#cordova-plugin-contacts)
- [Installation](#installation-3)
- [Firefox OS Quirks](#firefox-os-quirks-2)
- [Windows Quirks](#windows-quirks-3)
- [Windows 8 Quirks](#windows-8-quirks)
- [navigator.contacts](#navigatorcontacts)
- [Methods](#methods)
- [Objects](#objects)
- [navigator.contacts.create](#navigatorcontactscreate)
- [Supported Platforms](#supported-platforms-6)
- [Example](#example-7)
- [navigator.contacts.find](#navigatorcontactsfind)
- [Parameters](#parameters)
- [Supported Platforms](#supported-platforms-7)
- [Example](#example-8)
- [Windows Quirks](#windows-quirks-4)
- [navigator.contacts.pickContact](#navigatorcontactspickcontact)
- [Parameters](#parameters-1)
- [Supported Platforms](#supported-platforms-8)
- [Example](#example-9)
- [Contact](#contact)
- [Properties](#properties)
- [Methods](#methods-1)
- [Supported Platforms](#supported-platforms-9)
- [Save Example](#save-example)
- [Clone Example](#clone-example)
- [Remove Example](#remove-example)
- [Android 2.X Quirks](#android-2x-quirks)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-1)
- [FirefoxOS Quirks](#firefoxos-quirks)
- [iOS Quirks](#ios-quirks-2)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks)
- [Windows Quirks](#windows-quirks-5)
- [ContactAddress](#contactaddress)
- [Properties](#properties-1)
- [Supported Platforms](#supported-platforms-10)
- [Example](#example-10)
- [Android 2.X Quirks](#android-2x-quirks-1)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-2)
- [FirefoxOS Quirks](#firefoxos-quirks-1)
- [iOS Quirks](#ios-quirks-3)
- [Windows 8 Quirks](#windows-8-quirks-1)
- [Windows Quirks](#windows-quirks-6)
- [ContactError](#contacterror)
- [Properties](#properties-2)
- [Constants](#constants)
- [ContactField](#contactfield)
- [Properties](#properties-3)
- [Supported Platforms](#supported-platforms-11)
- [Example](#example-11)
- [Android Quirks](#android-quirks-3)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-3)
- [iOS Quirks](#ios-quirks-4)
- [Windows8 Quirks](#windows8-quirks)
- [Windows Quirks](#windows-quirks-7)
- [ContactName](#contactname)
- [Properties](#properties-4)
- [Supported Platforms](#supported-platforms-12)
- [Example](#example-12)
- [Android Quirks](#android-quirks-4)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-4)
- [FirefoxOS Quirks](#firefoxos-quirks-2)
- [iOS Quirks](#ios-quirks-5)
- [Windows 8 Quirks](#windows-8-quirks-2)
- [Windows Quirks](#windows-quirks-8)
- [ContactOrganization](#contactorganization)
- [Properties](#properties-5)
- [Supported Platforms](#supported-platforms-13)
- [Example](#example-13)
- [Android 2.X Quirks](#android-2x-quirks-2)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-5)
- [Firefox OS Quirks](#firefox-os-quirks-3)
- [iOS Quirks](#ios-quirks-6)
- [Windows Quirks](#windows-quirks-9)
- [cordova-plugin-device](#cordova-plugin-device)
- [Installation](#installation-4)
- [Properties](#properties-6)
- [device.cordova](#devicecordova)
- [Supported Platforms](#supported-platforms-14)
- [device.model](#devicemodel)
- [Supported Platforms](#supported-platforms-15)
- [Quick Example](#quick-example)
- [Android Quirks](#android-quirks-5)
- [Tizen Quirks](#tizen-quirks-2)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-2)
- [device.platform](#deviceplatform)
- [Supported Platforms](#supported-platforms-16)
- [Quick Example](#quick-example-1)
- [Windows Phone 7 Quirks](#windows-phone-7-quirks-1)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-1)
- [device.uuid](#deviceuuid)
- [Description](#description-6)
- [Supported Platforms](#supported-platforms-17)
- [Quick Example](#quick-example-2)
- [iOS Quirk](#ios-quirk)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-3)
- [device.version](#deviceversion)
- [Supported Platforms](#supported-platforms-18)
- [Quick Example](#quick-example-3)
- [cordova-plugin-device-motion](#cordova-plugin-device-motion)
- [Installation](#installation-5)
- [Supported Platforms](#supported-platforms-19)
- [Methods](#methods-2)
- [Objects](#objects-1)
- [navigator.accelerometer.getCurrentAcceleration](#navigatoraccelerometergetcurrentacceleration)
- [Example](#example-14)
- [Browser Quirks](#browser-quirks-4)
- [iOS Quirks](#ios-quirks-7)
- [navigator.accelerometer.watchAcceleration](#navigatoraccelerometerwatchacceleration)
- [Example](#example-15)
- [iOS Quirks](#ios-quirks-8)
- [navigator.accelerometer.clearWatch](#navigatoraccelerometerclearwatch)
- [Example](#example-16)
- [Acceleration](#acceleration)
- [Properties](#properties-7)
- [cordova-plugin-device-orientation](#cordova-plugin-device-orientation)
- [Installation](#installation-6)
- [Supported Platforms](#supported-platforms-20)
- [Methods](#methods-3)
- [navigator.compass.getCurrentHeading](#navigatorcompassgetcurrentheading)
- [Example](#example-17)
- [navigator.compass.watchHeading](#navigatorcompasswatchheading)
- [Example](#example-18)
- [Browser Quirks](#browser-quirks-5)
- [iOS Quirks](#ios-quirks-9)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-2)
- [Android Quirks](#android-quirks-6)
- [Firefox OS Quirks](#firefox-os-quirks-4)
- [Tizen Quirks](#tizen-quirks-3)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-4)
- [navigator.compass.clearWatch](#navigatorcompassclearwatch)
- [Example](#example-19)
- [CompassHeading](#compassheading)
- [Properties](#properties-8)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-3)
- [Android Quirks](#android-quirks-7)
- [Firefox OS Quirks](#firefox-os-quirks-5)
- [iOS Quirks](#ios-quirks-10)
- [CompassError](#compasserror)
- [Properties](#properties-9)
- [Constants](#constants-1)
- [cordova-plugin-dialogs](#cordova-plugin-dialogs)
- [Installation](#installation-7)
- [Methods](#methods-4)
- [navigator.notification.alert](#navigatornotificationalert)
- [Example](#example-20)
- [Supported Platforms](#supported-platforms-21)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-5)
- [Firefox OS Quirks:](#firefox-os-quirks)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-6)
- [navigator.notification.confirm](#navigatornotificationconfirm)
- [confirmCallback](#confirmcallback)
- [Example](#example-21)
- [Supported Platforms](#supported-platforms-22)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-6)
- [Windows Quirks](#windows-quirks-10)
- [Firefox OS Quirks:](#firefox-os-quirks-1)
- [navigator.notification.prompt](#navigatornotificationprompt)
- [promptCallback](#promptcallback)
- [Example](#example-22)
- [Supported Platforms](#supported-platforms-23)
- [Android Quirks](#android-quirks-8)
- [Windows Quirks](#windows-quirks-11)
- [Firefox OS Quirks:](#firefox-os-quirks-2)
- [navigator.notification.beep](#navigatornotificationbeep)
- [Example](#example-23)
- [Supported Platforms](#supported-platforms-24)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-4)
- [Android Quirks](#android-quirks-9)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-7)
- [Tizen Quirks](#tizen-quirks-4)
- [cordova-plugin-file](#cordova-plugin-file)
- [Installation](#installation-8)
- [Supported Platforms](#supported-platforms-25)
- [Where to Store Files](#where-to-store-files)
- [File System Layouts](#file-system-layouts)
- [iOS File System Layout](#ios-file-system-layout)
- [Android File System Layout](#android-file-system-layout)
- [BlackBerry 10 File System Layout](#blackberry-10-file-system-layout)
- [OS X File System Layout](#os-x-file-system-layout)
- [Android Quirks](#android-quirks-10)
- [Android Persistent storage location](#android-persistent-storage-location)
- [Slow recursive operations for /android_asset](#slow-recursive-operations-for-android_asset)
- [iOS Quirks](#ios-quirks-11)
- [iOS Persistent storage location](#ios-persistent-storage-location)
- [Firefox OS Quirks](#firefox-os-quirks-6)
- [Browser Quirks](#browser-quirks-6)
- [Common quirks and remarks](#common-quirks-and-remarks)
- [Chrome quirks](#chrome-quirks)
- [IndexedDB-based impl quirks (Firefox and IE)](#indexeddb-based-impl-quirks-firefox-and-ie)
- [Upgrading Notes](#upgrading-notes)
- [cdvfile protocol](#cdvfile-protocol)
- [List of Error Codes and Meanings](#list-of-error-codes-and-meanings)
- [Configuring the Plugin (Optional)](#configuring-the-plugin-optional)
- [Android](#android)
- [iOS](#ios)
- [cordova-plugin-file-transfer](#cordova-plugin-file-transfer)
- [Installation](#installation-9)
- [Supported Platforms](#supported-platforms-26)
- [FileTransfer](#filetransfer)
- [Properties](#properties-10)
- [Methods](#methods-5)
- [upload](#upload)
- [Example](#example-24)
- [Example with Upload Headers and Progress Events (Android and iOS only)](#example-with-upload-headers-and-progress-events-android-and-ios-only)
- [FileUploadResult](#fileuploadresult)
- [Properties](#properties-11)
- [iOS Quirks](#ios-quirks-12)
- [Browser Quirks](#browser-quirks-7)
- [download](#download)
- [Example](#example-25)
- [WP8 Quirks](#wp8-quirks)
- [Browser Quirks](#browser-quirks-8)
- [abort](#abort)
- [Example](#example-26)
- [FileTransferError](#filetransfererror)
- [Properties](#properties-12)
- [Constants](#constants-2)
- [Backwards Compatibility Notes](#backwards-compatibility-notes)
[cordova-plugin-geolocation](#cordova-plugin-geolocation)
- [Installation](#installation-10)
- [Supported Platforms](#supported-platforms-27)
- [Methods](#methods-6)
- [Objects (Read-Only)](#objects-read-only)
- [navigator.geolocation.getCurrentPosition](#navigatorgeolocationgetcurrentposition)
- [Parameters](#parameters-2)
- [Example](#example-27)
- [navigator.geolocation.watchPosition](#navigatorgeolocationwatchposition)
- [Parameters](#parameters-3)
- [Returns](#returns)
- [Example](#example-28)
- [geolocationOptions](#geolocationoptions)
- [Options](#options)
- [Android Quirks](#android-quirks-11)
- [navigator.geolocation.clearWatch](#navigatorgeolocationclearwatch)
- [Parameters](#parameters-4)
- [Example](#example-29)
- [Position](#position)
- [Properties](#properties-13)
- [Coordinates](#coordinates)
- [Properties](#properties-14)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-5)
- [Android Quirks](#android-quirks-12)
- [PositionError](#positionerror)
- [Properties](#properties-15)
- [Constants](#constants-3)
[cordova-plugin-globalization](#cordova-plugin-globalization)
- [Installation](#installation-11)
- [Objects](#objects-2)
- [Methods](#methods-7)
- [navigator.globalization.getPreferredLanguage](#navigatorglobalizationgetpreferredlanguage)
- [Description](#description-7)
- [Supported Platforms](#supported-platforms-28)
- [Example](#example-30)
- [Android Quirks](#android-quirks-13)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-2)
- [Windows Quirks](#windows-quirks-12)
- [Browser Quirks](#browser-quirks-9)
- [navigator.globalization.getLocaleName](#navigatorglobalizationgetlocalename)
- [Description](#description-8)
- [Supported Platforms](#supported-platforms-29)
- [Example](#example-31)
- [Android Quirks](#android-quirks-14)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-3)
- [Windows Quirks](#windows-quirks-13)
- [Browser Quirks](#browser-quirks-10)
- [navigator.globalization.dateToString](#navigatorglobalizationdatetostring)
- [Description](#description-9)
- [Supported Platforms](#supported-platforms-30)
- [Example](#example-32)
- [Android Quirks](#android-quirks-15)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-4)
- [Windows Quirks](#windows-quirks-14)
- [Browser Quirks](#browser-quirks-11)
- [Firefox OS Quirks](#firefox-os-quirks-7)
- [navigator.globalization.getCurrencyPattern](#navigatorglobalizationgetcurrencypattern)
- [Description](#description-10)
- [Supported Platforms](#supported-platforms-31)
- [Example](#example-33)
- [Windows Quirks](#windows-quirks-15)
- [navigator.globalization.getDateNames](#navigatorglobalizationgetdatenames)
- [Description](#description-11)
- [Supported Platforms](#supported-platforms-32)
- [Example](#example-34)
- [Firefox OS Quirks](#firefox-os-quirks-8)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-5)
- [Windows Quirks](#windows-quirks-16)
- [Browser Quirks](#browser-quirks-12)
- [navigator.globalization.getDatePattern](#navigatorglobalizationgetdatepattern)
- [Description](#description-12)
- [Supported Platforms](#supported-platforms-33)
- [Example](#example-35)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-6)
- [Windows Quirks](#windows-quirks-17)
- [Browser Quirks](#browser-quirks-13)
- [navigator.globalization.getFirstDayOfWeek](#navigatorglobalizationgetfirstdayofweek)
- [Description](#description-13)
- [Supported Platforms](#supported-platforms-34)
- [Example](#example-36)
- [ Windows Quirks](#windows-quirks)
- [Browser Quirks](#browser-quirks-14)
- [navigator.globalization.getNumberPattern](#navigatorglobalizationgetnumberpattern)
- [Description](#description-14)
- [Supported Platforms](#supported-platforms-35)
- [Example](#example-37)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-7)
- [Windows Quirks](#windows-quirks-18)
- [Browser Quirks](#browser-quirks-15)
- [navigator.globalization.isDayLightSavingsTime](#navigatorglobalizationisdaylightsavingstime)
- [Description](#description-15)
- [Supported Platforms](#supported-platforms-36)
- [Example](#example-38)
- [navigator.globalization.numberToString](#navigatorglobalizationnumbertostring)
- [Description](#description-16)
- [Supported Platforms](#supported-platforms-37)
- [Example](#example-39)
- [Windows Quirks](#windows-quirks-19)
- [Browser Quirks](#browser-quirks-16)
- [navigator.globalization.stringToDate](#navigatorglobalizationstringtodate)
- [Description](#description-17)
- [Supported Platforms](#supported-platforms-38)
- [Example](#example-40)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-8)
- [Windows Quirks](#windows-quirks-20)
- [Browser Quirks](#browser-quirks-17)
- [navigator.globalization.stringToNumber](#navigatorglobalizationstringtonumber)
- [Description](#description-18)
- [Supported Platforms](#supported-platforms-39)
- [Example](#example-41)
- [Windows Phone 8 Quirks ](#windows-phone-8-quirks)
- [Windows Quirks ](#windows-quirks)
- [GlobalizationError](#globalizationerror)
- [Properties](#properties-16)
- [Description](#description-19)
- [Supported Platforms](#supported-platforms-40)
- [Example](#example-42)
[cordova-plugin-inappbrowser](#cordova-plugin-inappbrowser)
- [Installation](#installation-12)
- [cordova.InAppBrowser.open](#cordovainappbrowseropen)
- [Supported Platforms](#supported-platforms-41)
- [Example](#example-43)
- [Firefox OS Quirks](#firefox-os-quirks-9)
- [Windows Quirks](#windows-quirks-21)
- [Browser Quirks](#browser-quirks-18)
- [InAppBrowser](#inappbrowser)
- [Methods](#methods-8)
- [addEventListener](#addeventlistener)
- [InAppBrowserEvent Properties](#inappbrowserevent-properties)
- [Supported Platforms](#supported-platforms-42)
- [Browser Quirks](#browser-quirks-19)
- [Quick Example](#quick-example-4)
- [removeEventListener](#removeeventlistener)
- [Supported Platforms](#supported-platforms-43)
- [Quick Example](#quick-example-5)
- [close](#close)
- [Supported Platforms](#supported-platforms-44)
- [Quick Example](#quick-example-6)
- [show](#show)
- [Supported Platforms](#supported-platforms-45)
- [Quick Example](#quick-example-7)
- [executeScript](#executescript)
- [Supported Platforms](#supported-platforms-46)
- [Quick Example](#quick-example-8)
- [Browser Quirks](#browser-quirks-20)
- [Windows Quirks](#windows-quirks-22)
- [insertCSS](#insertcss)
- [Supported Platforms](#supported-platforms-47)
- [Quick Example](#quick-example-9)
[cordova-plugin-legacy-whitelist](#cordova-plugin-legacy-whitelist)
- [Usage:](#usage)
[cordova-plugin-media](#cordova-plugin-media)
- [Installation](#installation-13)
- [Supported Platforms](#supported-platforms-48)
- [Windows Phone Quirks](#windows-phone-quirks)
- [Media](#media)
- [Parameters](#parameters-5)
- [Constants](#constants-4)
- [Methods](#methods-9)
- [Additional ReadOnly Parameters](#additional-readonly-parameters)
- [media.getCurrentPosition](#mediagetcurrentposition)
- [Parameters](#parameters-6)
- [Quick Example](#quick-example-10)
- [media.getDuration](#mediagetduration)
- [Quick Example](#quick-example-11)
- [media.pause](#mediapause)
- [Quick Example](#quick-example-12)
- [media.play](#mediaplay)
- [Quick Example](#quick-example-13)
- [iOS Quirks](#ios-quirks-13)
- [media.release](#mediarelease)
- [Quick Example](#quick-example-14)
- [media.seekTo](#mediaseekto)
- [Parameters](#parameters-7)
- [Quick Example](#quick-example-15)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-7)
- [media.setVolume](#mediasetvolume)
- [Parameters](#parameters-8)
- [Supported Platforms](#supported-platforms-49)
- [Quick Example](#quick-example-16)
- [media.startRecord](#mediastartrecord)
- [Supported Platforms](#supported-platforms-50)
- [Quick Example](#quick-example-17)
- [Android Quirks](#android-quirks-16)
- [iOS Quirks](#ios-quirks-14)
- [Windows Quirks](#windows-quirks-23)
- [Tizen Quirks](#tizen-quirks-5)
- [media.stop](#mediastop)
- [Quick Example](#quick-example-18)
- [media.stopRecord](#mediastoprecord)
- [Supported Platforms](#supported-platforms-51)
- [Quick Example](#quick-example-19)
- [Tizen Quirks](#tizen-quirks-6)
- [MediaError](#mediaerror)
- [Properties](#properties-17)
- [Constants](#constants-5)
[cordova-plugin-media-capture](#cordova-plugin-media-capture)
- [Installation](#installation-14)
- [Supported Platforms](#supported-platforms-52)
- [Objects](#objects-3)
- [Methods](#methods-10)
- [Properties](#properties-18)
- [capture.captureAudio](#capturecaptureaudio)
- [Description](#description-20)
- [Supported Platforms](#supported-platforms-53)
- [Example](#example-44)
- [iOS Quirks](#ios-quirks-15)
- [Windows Phone 7 and 8 Quirks](#windows-phone-7-and-8-quirks-8)
- [CaptureAudioOptions](#captureaudiooptions)
- [Properties](#properties-19)
- [Example](#example-45)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-6)
- [Android Quirks](#android-quirks-17)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-8)
- [iOS Quirks](#ios-quirks-16)
- [capture.captureImage](#capturecaptureimage)
- [Description](#description-21)
- [Supported Platforms](#supported-platforms-54)
- [Windows Phone 7 Quirks](#windows-phone-7-quirks-2)
- [Browser Quirks](#browser-quirks-21)
- [Example](#example-46)
- [CaptureImageOptions](#captureimageoptions)
- [Properties](#properties-20)
- [Example](#example-47)
- [iOS Quirks](#ios-quirks-17)
- [capture.captureVideo](#capturecapturevideo)
- [Description](#description-22)
- [Supported Platforms](#supported-platforms-55)
- [Example](#example-48)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-9)
- [CaptureVideoOptions](#capturevideooptions)
- [Properties](#properties-21)
- [Example](#example-49)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-10)
- [iOS Quirks](#ios-quirks-18)
- [Android Quirks](#android-quirks-18)
- [Example ( Android w/ quality )](#example--android-w-quality-)
- [CaptureCB](#capturecb)
- [Description](#description-23)
- [Example](#example-50)
- [CaptureError](#captureerror)
- [Properties](#properties-22)
- [Constants](#constants-6)
- [CaptureErrorCB](#captureerrorcb)
- [Description](#description-24)
- [Example](#example-51)
- [ConfigurationData](#configurationdata)
- [Description](#description-25)
- [Properties](#properties-23)
- [Example](#example-52)
- [MediaFile.getFormatData](#mediafilegetformatdata)
- [Description](#description-26)
- [Supported Platforms](#supported-platforms-56)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-7)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-11)
- [Android Quirks](#android-quirks-19)
- [iOS Quirks](#ios-quirks-19)
- [MediaFile](#mediafile)
- [Properties](#properties-24)
- [Methods](#methods-11)
- [MediaFileData](#mediafiledata)
- [Properties](#properties-25)
- [BlackBerry 10 Quirks](#blackberry-10-quirks-12)
- [Amazon Fire OS Quirks](#amazon-fire-os-quirks-8)
- [Android Quirks](#android-quirks-20)
- [iOS Quirks](#ios-quirks-20)
[cordova-plugin-network-information](#cordova-plugin-network-information)
- [Installation](#installation-15)
- [Supported Platforms](#supported-platforms-57)
- [Connection](#connection)
- [Properties](#properties-26)
- [Constants](#constants-7)
- [connection.type](#connectiontype)
- [Quick Example](#quick-example-20)
- [API Change](#api-change)
- [iOS Quirks](#ios-quirks-21)
- [Windows Phone Quirks](#windows-phone-quirks-1)
- [Windows Quirks](#windows-quirks-24)
- [Tizen Quirks](#tizen-quirks-7)
- [Firefox OS Quirks](#firefox-os-quirks-10)
- [Browser Quirks](#browser-quirks-22)
- [Network-related Events](#network-related-events)
- [offline](#offline)
- [Details](#details)
- [Quick Example](#quick-example-21)
- [iOS Quirks](#ios-quirks-22)
- [Windows Phone 7 Quirks](#windows-phone-7-quirks-3)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-9)
- [online](#online)
- [Details](#details-1)
- [Quick Example](#quick-example-22)
- [iOS Quirks](#ios-quirks-23)
- [Windows Phone 7 Quirks](#windows-phone-7-quirks-4)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-10)
[cordova-plugin-splashscreen](#cordova-plugin-splashscreen)
- [Installation](#installation-16)
- [Supported Platforms](#supported-platforms-58)
- [Preferences](#preferences)
- [config.xml](#configxml)
- [Android Quirks](#android-quirks-21)
- [Browser Quirks](#browser-quirks-23)
- [iOS Quirks](#ios-quirks-24)
- [Methods](#methods-12)
- [splashscreen.hide](#splashscreenhide)
- [BlackBerry 10, WP8, iOS Quirk](#blackberry-10-wp8-ios-quirk)
- [splashscreen.show](#splashscreenshow)
[cordova-plugin-statusbar](#cordova-plugin-statusbar)
- [StatusBar](#statusbar)
- [Installation](#installation-17)
- [Preferences](#preferences-1)
- [config.xml](#configxml-1)
- [Android Quirks](#android-quirks-22)
- [Hiding at startup](#hiding-at-startup)
- [Methods](#methods-13)
- [Properties](#properties-27)
- [Permissions](#permissions)
- [config.xml](#configxml-2)
- [StatusBar.overlaysWebView](#statusbaroverlayswebview)
- [Description](#description-27)
- [Supported Platforms](#supported-platforms-59)
- [Quick Example](#quick-example-23)
- [StatusBar.styleDefault](#statusbarstyledefault)
- [Supported Platforms](#supported-platforms-60)
- [StatusBar.styleLightContent](#statusbarstylelightcontent)
- [Supported Platforms](#supported-platforms-61)
- [StatusBar.styleBlackTranslucent](#statusbarstyleblacktranslucent)
- [Supported Platforms](#supported-platforms-62)
- [StatusBar.styleBlackOpaque](#statusbarstyleblackopaque)
- [Supported Platforms](#supported-platforms-63)
- [StatusBar.backgroundColorByName](#statusbarbackgroundcolorbyname)
- [Supported Platforms](#supported-platforms-64)
- [StatusBar.backgroundColorByHexString](#statusbarbackgroundcolorbyhexstring)
- [Supported Platforms](#supported-platforms-65)
- [StatusBar.hide](#statusbarhide)
- [Supported Platforms](#supported-platforms-66)
- [StatusBar.show](#statusbarshow)
- [Supported Platforms](#supported-platforms-67)
- [StatusBar.isVisible](#statusbarisvisible)
- [Supported Platforms](#supported-platforms-68)
- [Cordova Plugin Test Framework](#cordova-plugin-test-framework)
- [TLDR; Try it](#tldr-try-it)
- [Writing Plugin Tests](#writing-plugin-tests)
- [Where do tests live?](#where-do-tests-live)
- [Defining Auto Tests](#defining-auto-tests)
- [Defining Manual Tests](#defining-manual-tests)
- [Example](#example-53)
- [Running Plugin Tests](#running-plugin-tests)
- [FAQ](#faq)
[cordova-plugin-vibration](#cordova-plugin-vibration)
- [Installation](#installation-18)
- [Supported Platforms](#supported-platforms-69)
- [vibrate (recommended)](#vibrate-recommended)
- [Standard vibrate](#standard-vibrate)
- [Example](#example-54)
- [iOS Quirks](#ios-quirks-25)
- [Windows and Blackberry Quirks](#windows-and-blackberry-quirks)
- [Vibrate with a pattern (Android and Windows only)](#vibrate-with-a-pattern-android-and-windows-only)
- [Example](#example-55)
- [Windows Phone 8 Quirks](#windows-phone-8-quirks-11)
- [Windows Quirks](#windows-quirks-25)
- [Cancel vibration (not supported in iOS)](#cancel-vibration-not-supported-in-ios)
- [*notification.vibrate (deprecated)](#notificationvibrate-deprecated)
- [Example](#example-56)
- [iOS Quirks](#ios-quirks-26)
- [*notification.vibrateWithPattern (deprecated)](#notificationvibratewithpattern-deprecated)
- [Example](#example-57)
- [*notification.cancelVibration (deprecated)](#notificationcancelvibration-deprecated)
[cordova-plugin-whitelist](#cordova-plugin-whitelist)
- [Supported Cordova Platforms](#supported-cordova-platforms)
- [Navigation Whitelist](#navigation-whitelist)
- [Intent Whitelist](#intent-whitelist)
- [Network Request Whitelist](#network-request-whitelist)
- [Content Security Policy](#content-security-policy)
- [cordova-labs plugins branch](#cordova-labs-plugins-branch)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-battery-status
This plugin provides an implementation of an old version of the [Battery Status Events API](http://www.w3.org/TR/2011/WD-battery-status-20110915/).
It adds the following three `window` events:
* batterystatus
* batterycritical
* batterylow
## Installation
cordova plugin add cordova-plugin-battery-status
## batterystatus
This event fires when the percentage of battery charge changes by at
least 1 percent, or if the device is plugged in or unplugged.
The battery status handler is passed an object that contains two
properties:
- __level__: The percentage of battery charge (0-100). _(Number)_
- __isPlugged__: A boolean that indicates whether the device is plugged in. _(Boolean)_
Applications typically should use `window.addEventListener` to
attach an event listener after the `deviceready` event fires.
### Supported Platforms
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Windows Phone 7 and 8
- Windows (Windows Phone 8.1 only)
- Tizen
- Firefox OS
- Browser
### Android and Amazon Fire OS Quirks
- Warning: the Android + Fire OS implementations are greedy and prolonged use will drain the user's battery.
### Windows Phone 7 and 8 Quirks
Windows Phone 7 does not provide native APIs to determine battery
level, so the `level` property is unavailable. The `isPlugged`
parameter _is_ supported.
### Windows Quirks
Windows Phone 8.1 does not support `isPlugged` parameter.
The `level` parameter _is_ supported.
### Browser Quirks
Supported browsers are Chrome, Firefox and Opera.
### Example
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
## batterycritical
The event fires when the percentage of battery charge has reached the
critical battery threshold. The value is device-specific.
The `batterycritical` handler is passed an object that contains two
properties:
- __level__: The percentage of battery charge (0-100). _(Number)_
- __isPlugged__: A boolean that indicates whether the device is plugged in. _(Boolean)_
Applications typically should use `window.addEventListener` to attach
an event listener once the `deviceready` event fires.
### Supported Platforms
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Tizen
- Firefox OS
- Windows (Windows Phone 8.1 only)
- Browser
### Windows Quirks
Windows Phone 8.1 will fire `batterycritical` event regardless of plugged state as it is not supported.
### Example
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
### Browser Quirks
Supported browsers are Chrome, Firefox and Opera.
## batterylow
The event fires when the percentage of battery charge has reached the
low battery threshold, device-specific value.
The `batterylow` handler is passed an object that contains two
properties:
- __level__: The percentage of battery charge (0-100). _(Number)_
- __isPlugged__: A boolean that indicates whether the device is plugged in. _(Boolean)_
Applications typically should use `window.addEventListener` to
attach an event listener once the `deviceready` event fires.
### Supported Platforms
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Tizen
- Firefox OS
- Windows (Windows Phone 8.1 only)
- Browser
### Windows Quirks
Windows Phone 8.1 will fire `batterylow` event regardless of plugged state as it is not supported.
### Example
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}
### Browser Quirks
Supported browsers are Chrome, Firefox and Opera.
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-camera
This plugin defines a global `navigator.camera` object, which provides an API for taking pictures and for choosing images from
the system's image library.
Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.camera);
}
## Installation
cordova plugin add cordova-plugin-camera
## API
- Camera
- navigator.camera.getPicture(success, fail, options)
- CameraOptions
- CameraPopoverHandle
- CameraPopoverOptions
- navigator.camera.cleanup
## navigator.camera.getPicture
Takes a photo using the camera, or retrieves a photo from the device's
image gallery. The image is passed to the success callback as a
base64-encoded `String`, or as the URI for the image file. The method
itself returns a `CameraPopoverHandle` object that can be used to
reposition the file selection popover.
navigator.camera.getPicture(cameraSuccess, cameraError, cameraOptions);
#### Description
The `camera.getPicture` function opens the device's default camera
application that allows users to snap pictures. This behavior occurs
by default, when `Camera.sourceType` equals
`Camera.PictureSourceType.CAMERA`. Once the user snaps the photo, the
camera application closes and the application is restored.
If `Camera.sourceType` is `Camera.PictureSourceType.PHOTOLIBRARY` or
`Camera.PictureSourceType.SAVEDPHOTOALBUM`, then a dialog displays
that allows users to select an existing image. The
`camera.getPicture` function returns a `CameraPopoverHandle` object,
which can be used to reposition the image selection dialog, for
example, when the device orientation changes.
The return value is sent to the `cameraSuccess` callback function, in
one of the following formats, depending on the specified
`cameraOptions`:
- A `String` containing the base64-encoded photo image.
- A `String` representing the image file location on local storage (default).
You can do whatever you want with the encoded image or URI, for
example:
- Render the image in an `<img>` tag, as in the example below
- Save the data locally (`LocalStorage`, [Lawnchair](http://brianleroux.github.com/lawnchair/), etc.)
- Post the data to a remote server
__NOTE__: Photo resolution on newer devices is quite good. Photos
selected from the device's gallery are not downscaled to a lower
quality, even if a `quality` parameter is specified. To avoid common
memory problems, set `Camera.destinationType` to `FILE_URI` rather
than `DATA_URL`.
#### Supported Platforms
![](doc/img/android-success.png) ![](doc/img/blackberry-success.png) ![](doc/img/browser-success.png) ![](doc/img/firefox-success.png) ![](doc/img/fireos-success.png) ![](doc/img/ios-success.png) ![](doc/img/windows-success.png) ![](doc/img/wp8-success.png) ![](doc/img/ubuntu-success.png)
#### Example
Take a photo and retrieve it as a base64-encoded image:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
Take a photo and retrieve the image's file location:
navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.FILE_URI });
function onSuccess(imageURI) {
var image = document.getElementById('myImage');
image.src = imageURI;
}
function onFail(message) {
alert('Failed because: ' + message);
}
#### Preferences (iOS)
- __CameraUsesGeolocation__ (boolean, defaults to false). For capturing JPEGs, set to true to get geolocation data in the EXIF header. This will trigger a request for geolocation permissions if set to true.
<preference name="CameraUsesGeolocation" value="false" />
#### Amazon Fire OS Quirks
Amazon Fire OS uses intents to launch the camera activity on the device to capture
images, and on phones with low memory, the Cordova activity may be killed. In this
scenario, the image may not appear when the cordova activity is restored.
#### Android Quirks
Android uses intents to launch the camera activity on the device to capture
images, and on phones with low memory, the Cordova activity may be killed. In this
scenario, the image may not appear when the Cordova activity is restored.
#### Browser Quirks
Can only return photos as base64-encoded image.
#### Firefox OS Quirks
Camera plugin is currently implemented using [Web Activities](https://hacks.mozilla.org/2013/01/introducing-web-activities/).
#### iOS Quirks
Including a JavaScript `alert()` in either of the callback functions
can cause problems. Wrap the alert within a `setTimeout()` to allow
the iOS image picker or popover to fully close before the alert
displays:
setTimeout(function() {
// do your thing here!
}, 0);
#### Windows Phone 7 Quirks
Invoking the native camera application while the device is connected
via Zune does not work, and triggers an error callback.
#### Tizen Quirks
Tizen only supports a `destinationType` of
`Camera.DestinationType.FILE_URI` and a `sourceType` of
`Camera.PictureSourceType.PHOTOLIBRARY`.
## CameraOptions
Optional parameters to customize the camera settings.
{ quality : 75,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false };
- __quality__: Quality of the saved image, expressed as a range of 0-100, where 100 is typically full resolution with no loss from file compression. The default is 50. _(Number)_ (Note that information about the camera's resolution is unavailable.)
- __destinationType__: Choose the format of the return value. The default is FILE_URI. Defined in `navigator.camera.DestinationType` _(Number)_
Camera.DestinationType = {
DATA_URL : 0, // Return image as base64-encoded string
FILE_URI : 1, // Return image file URI
NATIVE_URI : 2 // Return image native URI (e.g., assets-library:// on iOS or content:// on Android)
};
- __sourceType__: Set the source of the picture. The default is CAMERA. Defined in `navigator.camera.PictureSourceType` _(Number)_
Camera.PictureSourceType = {
PHOTOLIBRARY : 0,
CAMERA : 1,
SAVEDPHOTOALBUM : 2
};
- __allowEdit__: Allow simple editing of image before selection. _(Boolean)_
- __encodingType__: Choose the returned image file's encoding. Default is JPEG. Defined in `navigator.camera.EncodingType` _(Number)_
Camera.EncodingType = {
JPEG : 0, // Return JPEG encoded image
PNG : 1 // Return PNG encoded image
};
- __targetWidth__: Width in pixels to scale image. Must be used with __targetHeight__. Aspect ratio remains constant. _(Number)_
- __targetHeight__: Height in pixels to scale image. Must be used with __targetWidth__. Aspect ratio remains constant. _(Number)_
- __mediaType__: Set the type of media to select from. Only works when `PictureSourceType` is `PHOTOLIBRARY` or `SAVEDPHOTOALBUM`. Defined in `nagivator.camera.MediaType` _(Number)_
Camera.MediaType = {
PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI
ALLMEDIA : 2 // allow selection from all media types
};
- __correctOrientation__: Rotate the image to correct for the orientation of the device during capture. _(Boolean)_
- __saveToPhotoAlbum__: Save the image to the photo album on the device after capture. _(Boolean)_
- __popoverOptions__: iOS-only options that specify popover location in iPad. Defined in `CameraPopoverOptions`.
- __cameraDirection__: Choose the camera to use (front- or back-facing). The default is BACK. Defined in `navigator.camera.Direction` _(Number)_
Camera.Direction = {
BACK : 0, // Use the back-facing camera
FRONT : 1 // Use the front-facing camera
};
#### Amazon Fire OS Quirks
- Any `cameraDirection` value results in a back-facing photo.
- Ignores the `allowEdit` parameter.
- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
#### Android Quirks
- Any `cameraDirection` value results in a back-facing photo.
- Android also uses the Crop Activity for allowEdit, even though crop should work and actually pass the cropped image back to Cordova, the only one that works consistently is the one bundled
with the Google Plus Photos application. Other crops may not work.
- `Camera.PictureSourceType.PHOTOLIBRARY` and `Camera.PictureSourceType.SAVEDPHOTOALBUM` both display the same photo album.
#### BlackBerry 10 Quirks
- Ignores the `quality` parameter.
- Ignores the `allowEdit` parameter.
- `Camera.MediaType` is not supported.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
#### Firefox OS Quirks
- Ignores the `quality` parameter.
- `Camera.DestinationType` is ignored and equals `1` (image file URI)
- Ignores the `allowEdit` parameter.
- Ignores the `PictureSourceType` parameter (user chooses it in a dialog window)
- Ignores the `encodingType`
- Ignores the `targetWidth` and `targetHeight`
- `Camera.MediaType` is not supported.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
#### iOS Quirks
- When using `destinationType.FILE_URI`, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends.
#### Tizen Quirks
- options not supported
- always returns a FILE URI
#### Windows Phone 7 and 8 Quirks
- Ignores the `allowEdit` parameter.
- Ignores the `correctOrientation` parameter.
- Ignores the `cameraDirection` parameter.
- Ignores the `saveToPhotoAlbum` parameter. IMPORTANT: All images taken with the wp7/8 cordova camera API are always copied to the phone's camera roll. Depending on the user's settings, this could also mean the image is auto-uploaded to their OneDrive. This could potentially mean the image is available to a wider audience than your app intended. If this a blocker for your application, you will need to implement the CameraCaptureTask as documented on msdn : [http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh394006.aspx)
You may also comment or up-vote the related issue in the [issue tracker](https://issues.apache.org/jira/browse/CB-2083)
- Ignores the `mediaType` property of `cameraOptions` as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.
## CameraError
onError callback function that provides an error message.
function(message) {
// Show a helpful message
}
#### Description
- __message__: The message is provided by the device's native code. _(String)_
## cameraSuccess
onSuccess callback function that provides the image data.
function(imageData) {
// Do something with the image
}
#### Description
- __imageData__: Base64 encoding of the image data, _or_ the image file URI, depending on `cameraOptions` in effect. _(String)_
#### Example
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
## CameraPopoverHandle
A handle to the popover dialog created by `navigator.camera.getPicture`.
#### Description
- __setPosition__: Set the position of the popover. Takes the `CameraPopoverOptions` that specify the new position.
#### Supported Platforms
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Example
var cameraPopoverHandle = navigator.camera.getPicture(onSuccess, onFail,
{ destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
popoverOptions: new CameraPopoverOptions(300, 300, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY)
});
// Reposition the popover if the orientation changes.
window.onorientationchange = function() {
var cameraPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, Camera.PopoverArrowDirection.ARROW_ANY);
cameraPopoverHandle.setPosition(cameraPopoverOptions);
}
## CameraPopoverOptions
iOS-only parameters that specify the anchor element location and arrow
direction of the popover when selecting images from an iPad's library
or album.
{ x : 0,
y : 32,
width : 320,
height : 480,
arrowDir : Camera.PopoverArrowDirection.ARROW_ANY
};
#### Description
- __x__: x pixel coordinate of screen element onto which to anchor the popover. _(Number)_
- __y__: y pixel coordinate of screen element onto which to anchor the popover. _(Number)_
- __width__: width, in pixels, of the screen element onto which to anchor the popover. _(Number)_
- __height__: height, in pixels, of the screen element onto which to anchor the popover. _(Number)_
- __arrowDir__: Direction the arrow on the popover should point. Defined in `Camera.PopoverArrowDirection` _(Number)_
Camera.PopoverArrowDirection = {
ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants
ARROW_DOWN : 2,
ARROW_LEFT : 4,
ARROW_RIGHT : 8,
ARROW_ANY : 15
};
Note that the size of the popover may change to adjust to the
direction of the arrow and orientation of the screen. Make sure to
account for orientation changes when specifying the anchor element
location.
## navigator.camera.cleanup
Removes intermediate photos taken by the camera from temporary
storage.
navigator.camera.cleanup( cameraSuccess, cameraError );
#### Description
Removes intermediate image files that are kept in temporary storage
after calling `camera.getPicture`. Applies only when the value of
`Camera.sourceType` equals `Camera.PictureSourceType.CAMERA` and the
`Camera.destinationType` equals `Camera.DestinationType.FILE_URI`.
#### Supported Platforms
![](doc/img/android-fail.png) ![](doc/img/blackberry-fail.png) ![](doc/img/browser-fail.png) ![](doc/img/firefox-fail.png) ![](doc/img/fireos-fail.png) ![](doc/img/ios-success.png) ![](doc/img/windows-fail.png) ![](doc/img/wp8-fail.png) ![](doc/img/ubuntu-fail.png)
#### Example
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-console
This plugin is meant to ensure that console.log() is as useful as it can be.
It adds additional function for iOS, Ubuntu, Windows Phone 8, and Windows. If
you are happy with how console.log() works for you, then you probably
don't need this plugin.
This plugin defines a global `console` object.
Although the object is in the global scope, features provided by this plugin
are not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("console.log works well");
}
## Installation
cordova plugin add cordova-plugin-console
### Android Quirks
On some platforms other than Android, console.log() will act on multiple
arguments, such as console.log("1", "2", "3"). However, Android will act only
on the first argument. Subsequent arguments to console.log() will be ignored.
This plugin is not the cause of that, it is a limitation of Android itself.
## Supported Methods
The plugin support following methods of the `console` object:
- `console.log`
- `console.error`
- `console.exception`
- `console.warn`
- `console.info`
- `console.debug`
- `console.assert`
- `console.dir`
- `console.dirxml`
- `console.time`
- `console.timeEnd`
- `console.table`
## Partially supported Methods
Methods of the `console` object which implemented, but behave different from browser implementation:
- `console.group`
- `console.groupCollapsed`
The grouping methods are just log name of the group and don't actually indicate grouping for later
calls to `console` object methods.
## Not supported Methods
Methods of the `console` object which are implemented, but do nothing:
- `console.clear`
- `console.trace`
- `console.groupEnd`
- `console.timeStamp`
- `console.profile`
- `console.profileEnd`
- `console.count`
## Supported formatting
The following formatting options available:
Format chars:
* `%j` - format arg as JSON
* `%o` - format arg as JSON
* `%c` - format arg as `''`. No color formatting could be done.
* `%%` - replace with `'%'`
any other char following `%` will format it's
arg via `toString()`.
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-contacts
This plugin defines a global `navigator.contacts` object, which provides access to the device contacts database.
Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.contacts);
}
__WARNING__: Collection and use of contact data raises
important privacy issues. Your app's privacy policy should discuss
how the app uses contact data and whether it is shared with any other
parties. Contact information is considered sensitive because it
reveals the people with whom a person communicates. Therefore, in
addition to the app's privacy policy, you should strongly consider
providing a just-in-time notice before the app accesses or uses
contact data, if the device operating system doesn't do so
already. That notice should provide the same information noted above,
as well as obtaining the user's permission (e.g., by presenting
choices for __OK__ and __No Thanks__). Note that some app
marketplaces may require the app to provide a just-in-time notice and
obtain the user's permission before accessing contact data. A
clear and easy-to-understand user experience surrounding the use of
contact data helps avoid user confusion and perceived misuse of
contact data. For more information, please see the Privacy Guide.
## Installation
This requires cordova 5.0+ ( current stable v1.0.0 )
cordova plugin add cordova-plugin-contacts
Older versions of cordova can still install via the __deprecated__ id ( stale v0.2.16 )
cordova plugin add org.apache.cordova.contacts
It is also possible to install via repo url directly ( unstable )
cordova plugin add https://github.com/apache/cordova-plugin-contacts.git
### Firefox OS Quirks
Create __www/manifest.webapp__ as described in
[Manifest Docs](https://developer.mozilla.org/en-US/Apps/Developing/Manifest).
Add relevant permisions.
There is also a need to change the webapp type to "privileged" - [Manifest Docs](https://developer.mozilla.org/en-US/Apps/Developing/Manifest#type).
__WARNING__: All privileged apps enforce [Content Security Policy](https://developer.mozilla.org/en-US/Apps/CSP) which forbids inline script. Initialize your application in another way.
"type": "privileged",
"permissions": {
"contacts": {
"access": "readwrite",
"description": "Describe why there is a need for such permission"
}
}
### Windows Quirks
**Prior to Windows 10:** Any contacts returned from `find` and `pickContact` methods are readonly, so your application cannot modify them.
`find` method available only on Windows Phone 8.1 devices.
**Windows 10 and above:** Contacts may be saved and will be saved to app-local contacts storage. Contacts may also be deleted.
### Windows 8 Quirks
Windows 8 Contacts are readonly. Via the Cordova API Contacts are not queryable/searchable, you should inform the user to pick a contact as a call to contacts.pickContact which will open the 'People' app where the user must choose a contact.
Any contacts returned are readonly, so your application cannot modify them.
## navigator.contacts
### Methods
- navigator.contacts.create
- navigator.contacts.find
- navigator.contacts.pickContact
### Objects
- Contact
- ContactName
- ContactField
- ContactAddress
- ContactOrganization
- ContactFindOptions
- ContactError
- ContactFieldType
## navigator.contacts.create
The `navigator.contacts.create` method is synchronous, and returns a new `Contact` object.
This method does not retain the Contact object in the device contacts
database, for which you need to invoke the `Contact.save` method.
### Supported Platforms
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
### Example
var myContact = navigator.contacts.create({"displayName": "Test User"});
## navigator.contacts.find
The `navigator.contacts.find` method executes asynchronously, querying the
device contacts database and returning an array of `Contact` objects.
The resulting objects are passed to the `contactSuccess` callback
function specified by the __contactSuccess__ parameter.
The __contactFields__ parameter specifies the fields to be used as a
search qualifier. A zero-length __contactFields__ parameter is invalid and results in
`ContactError.INVALID_ARGUMENT_ERROR`. A __contactFields__ value of
`"*"` searches all contact fields.
The __contactFindOptions.filter__ string can be used as a search
filter when querying the contacts database. If provided, a
case-insensitive, partial value match is applied to each field
specified in the __contactFields__ parameter. If there's a match for
_any_ of the specified fields, the contact is returned. Use __contactFindOptions.desiredFields__
parameter to control which contact properties must be returned back.
### Parameters
- __contactFields__: Contact fields to use as a search qualifier. _(DOMString[])_ [Required]
- __contactSuccess__: Success callback function invoked with the array of Contact objects returned from the database. [Required]
- __contactError__: Error callback function, invoked when an error occurs. [Optional]
- __contactFindOptions__: Search options to filter navigator.contacts. [Optional]
Keys include:
- __filter__: The search string used to find navigator.contacts. _(DOMString)_ (Default: `""`)
- __multiple__: Determines if the find operation returns multiple navigator.contacts. _(Boolean)_ (Default: `false`)
- __desiredFields__: Contact fields to be returned back. If specified, the resulting `Contact` object only features values for these fields. _(DOMString[])_ [Optional]
- __hasPhoneNumber__(Android only): Filters the search to only return contacts with a phone number informed. _(Boolean)_ (Default: `false`)
### Supported Platforms
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows (Windows Phone 8.1 and Windows 10)
### Example
function onSuccess(contacts) {
alert('Found ' + contacts.length + ' contacts.');
};
function onError(contactError) {
alert('onError!');
};
// find all contacts with 'Bob' in any name field
var options = new ContactFindOptions();
options.filter = "Bob";
options.multiple = true;
options.desiredFields = [navigator.contacts.fieldType.id];
options.hasPhoneNumber = true;
var fields = [navigator.contacts.fieldType.displayName, navigator.contacts.fieldType.name];
navigator.contacts.find(fields, onSuccess, onError, options);
### Windows Quirks
- `__contactFields__` is not supported and will be ignored. `find` method will always attempt to match the name, email address, or phone number of a contact.
## navigator.contacts.pickContact
The `navigator.contacts.pickContact` method launches the Contact Picker to select a single contact.
The resulting object is passed to the `contactSuccess` callback
function specified by the __contactSuccess__ parameter.
### Parameters
- __contactSuccess__: Success callback function invoked with the single Contact object. [Required]
- __contactError__: Error callback function, invoked when an error occurs. [Optional]
### Supported Platforms
- Android
- iOS
- Windows Phone 8
- Windows 8
- Windows
### Example
navigator.contacts.pickContact(function(contact){
console.log('The following contact has been selected:' + JSON.stringify(contact));
},function(err){
console.log('Error: ' + err);
});
## Contact
The `Contact` object represents a user's contact. Contacts can be
created, stored, or removed from the device contacts database.
Contacts can also be retrieved (individually or in bulk) from the
database by invoking the `navigator.contacts.find` method.
__NOTE__: Not all of the contact fields listed above are supported on
every device platform. Please check each platform's _Quirks_ section
for details.
### Properties
- __id__: A globally unique identifier. _(DOMString)_
- __displayName__: The name of this Contact, suitable for display to end users. _(DOMString)_
- __name__: An object containing all components of a persons name. _(ContactName)_
- __nickname__: A casual name by which to address the contact. _(DOMString)_
- __phoneNumbers__: An array of all the contact's phone numbers. _(ContactField[])_
- __emails__: An array of all the contact's email addresses. _(ContactField[])_
- __addresses__: An array of all the contact's addresses. _(ContactAddress[])_
- __ims__: An array of all the contact's IM addresses. _(ContactField[])_
- __organizations__: An array of all the contact's organizations. _(ContactOrganization[])_
- __birthday__: The birthday of the contact. _(Date)_
- __note__: A note about the contact. _(DOMString)_
- __photos__: An array of the contact's photos. _(ContactField[])_
- __categories__: An array of all the user-defined categories associated with the contact. _(ContactField[])_
- __urls__: An array of web pages associated with the contact. _(ContactField[])_
### Methods
- __clone__: Returns a new `Contact` object that is a deep copy of the calling object, with the `id` property set to `null`.
- __remove__: Removes the contact from the device contacts database, otherwise executes an error callback with a `ContactError` object.
- __save__: Saves a new contact to the device contacts database, or updates an existing contact if a contact with the same __id__ already exists.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
### Save Example
function onSuccess(contact) {
alert("Save Success");
};
function onError(contactError) {
alert("Error = " + contactError.code);
};
// create a new contact object
var contact = navigator.contacts.create();
contact.displayName = "Plumber";
contact.nickname = "Plumber"; // specify both to support all devices
// populate some fields
var name = new ContactName();
name.givenName = "Jane";
name.familyName = "Doe";
contact.name = name;
// save to device
contact.save(onSuccess,onError);
### Clone Example
// clone the contact object
var clone = contact.clone();
clone.name.givenName = "John";
console.log("Original contact name = " + contact.name.givenName);
console.log("Cloned contact name = " + clone.name.givenName);
### Remove Example
function onSuccess() {
alert("Removal Success");
};
function onError(contactError) {
alert("Error = " + contactError.code);
};
// remove the contact from the device
contact.remove(onSuccess,onError);
### Android 2.X Quirks
- __categories__: Not supported on Android 2.X devices, returning `null`.
### BlackBerry 10 Quirks
- __id__: Assigned by the device when saving the contact.
### FirefoxOS Quirks
- __categories__: Partially supported. Fields __pref__ and __type__ are returning `null`
- __ims__: Not supported
- __photos__: Not supported
### iOS Quirks
- __displayName__: Not supported on iOS, returning `null` unless there is no `ContactName` specified, in which case it returns the composite name, __nickname__ or `""`, respectively.
- __birthday__: Must be input as a JavaScript `Date` object, the same way it is returned.
- __photos__: Returns a File URL to the image, which is stored in the application's temporary directory. Contents of the temporary directory are removed when the application exits.
- __categories__: This property is currently not supported, returning `null`.
### Windows Phone 8 Quirks
- __displayName__: When creating a contact, the value provided for the display name parameter differs from the display name retrieved when finding the contact.
- __urls__: When creating a contact, users can input and save more than one web address, but only one is available when searching the contact.
- __phoneNumbers__: The _pref_ option is not supported. The _type_ is not supported in a _find_ operation. Only one `phoneNumber` is allowed for each _type_.
- __emails__: The _pref_ option is not supported. Home and personal references same email entry. Only one entry is allowed for each _type_.
- __addresses__: Supports only work, and home/personal _type_. The home and personal _type_ reference the same address entry. Only one entry is allowed for each _type_.
- __organizations__: Only one is allowed, and does not support the _pref_, _type_, and _department_ attributes.
- __note__: Not supported, returning `null`.
- __ims__: Not supported, returning `null`.
- __birthdays__: Not supported, returning `null`.
- __categories__: Not supported, returning `null`.
- __remove__: Method is not supported
### Windows Quirks
- __photos__: Returns a File URL to the image, which is stored in the application's temporary directory.
- __birthdays__: Not supported, returning `null`.
- __categories__: Not supported, returning `null`.
- __remove__: Method is only supported in Windows 10 or above.
## ContactAddress
The `ContactAddress` object stores the properties of a single address
of a contact. A `Contact` object may include more than one address in
a `ContactAddress[]` array.
### Properties
- __pref__: Set to `true` if this `ContactAddress` contains the user's preferred value. _(boolean)_
- __type__: A string indicating what type of field this is, _home_ for example. _(DOMString)_
- __formatted__: The full address formatted for display. _(DOMString)_
- __streetAddress__: The full street address. _(DOMString)_
- __locality__: The city or locality. _(DOMString)_
- __region__: The state or region. _(DOMString)_
- __postalCode__: The zip code or postal code. _(DOMString)_
- __country__: The country name. _(DOMString)_
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
### Example
// display the address information for all contacts
function onSuccess(contacts) {
for (var i = 0; i < contacts.length; i++) {
for (var j = 0; j < contacts[i].addresses.length; j++) {
alert("Pref: " + contacts[i].addresses[j].pref + "\n" +
"Type: " + contacts[i].addresses[j].type + "\n" +
"Formatted: " + contacts[i].addresses[j].formatted + "\n" +
"Street Address: " + contacts[i].addresses[j].streetAddress + "\n" +
"Locality: " + contacts[i].addresses[j].locality + "\n" +
"Region: " + contacts[i].addresses[j].region + "\n" +
"Postal Code: " + contacts[i].addresses[j].postalCode + "\n" +
"Country: " + contacts[i].addresses[j].country);
}
}
};
function onError(contactError) {
alert('onError!');
};
// find all contacts
var options = new ContactFindOptions();
options.filter = "";
var filter = ["displayName", "addresses"];
navigator.contacts.find(filter, onSuccess, onError, options);
### Android 2.X Quirks
- __pref__: Not supported, returning `false` on Android 2.X devices.
### BlackBerry 10 Quirks
- __pref__: Not supported on BlackBerry devices, returning `false`.
- __type__: Partially supported. Only one each of _Work_ and _Home_ type addresses can be stored per contact.
- __formatted__: Partially supported. Returns a concatenation of all BlackBerry address fields.
- __streetAddress__: Supported. Returns a concatenation of BlackBerry __address1__ and __address2__ address fields.
- __locality__: Supported. Stored in BlackBerry __city__ address field.
- __region__: Supported. Stored in BlackBerry __stateProvince__ address field.
- __postalCode__: Supported. Stored in BlackBerry __zipPostal__ address field.
- __country__: Supported.
### FirefoxOS Quirks
- __formatted__: Currently not supported
### iOS Quirks
- __pref__: Not supported on iOS devices, returning `false`.
- __formatted__: Currently not supported.
### Windows 8 Quirks
- __pref__: Not supported
### Windows Quirks
- __pref__: Not supported
## ContactError
The `ContactError` object is returned to the user through the
`contactError` callback function when an error occurs.
### Properties
- __code__: One of the predefined error codes listed below.
### Constants
- `ContactError.UNKNOWN_ERROR` (code 0)
- `ContactError.INVALID_ARGUMENT_ERROR` (code 1)
- `ContactError.TIMEOUT_ERROR` (code 2)
- `ContactError.PENDING_OPERATION_ERROR` (code 3)
- `ContactError.IO_ERROR` (code 4)
- `ContactError.NOT_SUPPORTED_ERROR` (code 5)
- `ContactError.PERMISSION_DENIED_ERROR` (code 20)
## ContactField
The `ContactField` object is a reusable component that represents
contact fields generically. Each `ContactField` object contains a
`value`, `type`, and `pref` property. A `Contact` object stores
several properties in `ContactField[]` arrays, such as phone numbers
and email addresses.
In most instances, there are no pre-determined values for a
`ContactField` object's __type__ attribute. For example, a phone
number can specify __type__ values of _home_, _work_, _mobile_,
_iPhone_, or any other value that is supported by a particular device
platform's contact database. However, for the `Contact` __photos__
field, the __type__ field indicates the format of the returned image:
__url__ when the __value__ attribute contains a URL to the photo
image, or _base64_ when the __value__ contains a base64-encoded image
string.
### Properties
- __type__: A string that indicates what type of field this is, _home_ for example. _(DOMString)_
- __value__: The value of the field, such as a phone number or email address. _(DOMString)_
- __pref__: Set to `true` if this `ContactField` contains the user's preferred value. _(boolean)_
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
### Example
// create a new contact
var contact = navigator.contacts.create();
// store contact phone numbers in ContactField[]
var phoneNumbers = [];
phoneNumbers[0] = new ContactField('work', '212-555-1234', false);
phoneNumbers[1] = new ContactField('mobile', '917-555-5432', true); // preferred number
phoneNumbers[2] = new ContactField('home', '203-555-7890', false);
contact.phoneNumbers = phoneNumbers;
// save the contact
contact.save();
### Android Quirks
- __pref__: Not supported, returning `false`.
### BlackBerry 10 Quirks
- __type__: Partially supported. Used for phone numbers.
- __value__: Supported.
- __pref__: Not supported, returning `false`.
### iOS Quirks
- __pref__: Not supported, returning `false`.
### Windows8 Quirks
- __pref__: Not supported, returning `false`.
### Windows Quirks
- __pref__: Not supported, returning `false`.
## ContactName
Contains different kinds of information about a `Contact` object's name.
### Properties
- __formatted__: The complete name of the contact. _(DOMString)_
- __familyName__: The contact's family name. _(DOMString)_
- __givenName__: The contact's given name. _(DOMString)_
- __middleName__: The contact's middle name. _(DOMString)_
- __honorificPrefix__: The contact's prefix (example _Mr._ or _Dr._) _(DOMString)_
- __honorificSuffix__: The contact's suffix (example _Esq._). _(DOMString)_
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
### Example
function onSuccess(contacts) {
for (var i = 0; i < contacts.length; i++) {
alert("Formatted: " + contacts[i].name.formatted + "\n" +
"Family Name: " + contacts[i].name.familyName + "\n" +
"Given Name: " + contacts[i].name.givenName + "\n" +
"Middle Name: " + contacts[i].name.middleName + "\n" +
"Suffix: " + contacts[i].name.honorificSuffix + "\n" +
"Prefix: " + contacts[i].name.honorificSuffix);
}
};
function onError(contactError) {
alert('onError!');
};
var options = new ContactFindOptions();
options.filter = "";
filter = ["displayName", "name"];
navigator.contacts.find(filter, onSuccess, onError, options);
### Android Quirks
- __formatted__: Partially supported, and read-only. Returns a concatenation of `honorificPrefix`, `givenName`, `middleName`, `familyName`, and `honorificSuffix`.
### BlackBerry 10 Quirks
- __formatted__: Partially supported. Returns a concatenation of BlackBerry __firstName__ and __lastName__ fields.
- __familyName__: Supported. Stored in BlackBerry __lastName__ field.
- __givenName__: Supported. Stored in BlackBerry __firstName__ field.
- __middleName__: Not supported, returning `null`.
- __honorificPrefix__: Not supported, returning `null`.
- __honorificSuffix__: Not supported, returning `null`.
### FirefoxOS Quirks
- __formatted__: Partially supported, and read-only. Returns a concatenation of `honorificPrefix`, `givenName`, `middleName`, `familyName`, and `honorificSuffix`.
### iOS Quirks
- __formatted__: Partially supported. Returns iOS Composite Name, but is read-only.
### Windows 8 Quirks
- __formatted__: This is the only name property, and is identical to `displayName`, and `nickname`
- __familyName__: not supported
- __givenName__: not supported
- __middleName__: not supported
- __honorificPrefix__: not supported
- __honorificSuffix__: not supported
### Windows Quirks
- __formatted__: It is identical to `displayName`
## ContactOrganization
The `ContactOrganization` object stores a contact's organization
properties. A `Contact` object stores one or more
`ContactOrganization` objects in an array.
### Properties
- __pref__: Set to `true` if this `ContactOrganization` contains the user's preferred value. _(boolean)_
- __type__: A string that indicates what type of field this is, _home_ for example. _(DOMString)
- __name__: The name of the organization. _(DOMString)_
- __department__: The department the contract works for. _(DOMString)_
- __title__: The contact's title at the organization. _(DOMString)_
### Supported Platforms
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows (Windows 8.1 and Windows Phone 8.1 devices only)
### Example
function onSuccess(contacts) {
for (var i = 0; i < contacts.length; i++) {
for (var j = 0; j < contacts[i].organizations.length; j++) {
alert("Pref: " + contacts[i].organizations[j].pref + "\n" +
"Type: " + contacts[i].organizations[j].type + "\n" +
"Name: " + contacts[i].organizations[j].name + "\n" +
"Department: " + contacts[i].organizations[j].department + "\n" +
"Title: " + contacts[i].organizations[j].title);
}
}
};
function onError(contactError) {
alert('onError!');
};
var options = new ContactFindOptions();
options.filter = "";
filter = ["displayName", "organizations"];
navigator.contacts.find(filter, onSuccess, onError, options);
### Android 2.X Quirks
- __pref__: Not supported by Android 2.X devices, returning `false`.
### BlackBerry 10 Quirks
- __pref__: Not supported by BlackBerry devices, returning `false`.
- __type__: Not supported by BlackBerry devices, returning `null`.
- __name__: Partially supported. The first organization name is stored in the BlackBerry __company__ field.
- __department__: Not supported, returning `null`.
- __title__: Partially supported. The first organization title is stored in the BlackBerry __jobTitle__ field.
### Firefox OS Quirks
- __pref__: Not supported
- __type__: Not supported
- __department__: Not supported
- Fields __name__ and __title__ stored in __org__ and __jobTitle__.
### iOS Quirks
- __pref__: Not supported on iOS devices, returning `false`.
- __type__: Not supported on iOS devices, returning `null`.
- __name__: Partially supported. The first organization name is stored in the iOS __kABPersonOrganizationProperty__ field.
- __department__: Partially supported. The first department name is stored in the iOS __kABPersonDepartmentProperty__ field.
- __title__: Partially supported. The first title is stored in the iOS __kABPersonJobTitleProperty__ field.
### Windows Quirks
- __pref__: Not supported, returning `false`.
- __type__: Not supported, returning `null`.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-device
This plugin defines a global `device` object, which describes the device's hardware and software.
Although the object is in the global scope, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Installation
cordova plugin add cordova-plugin-device
## Properties
- device.cordova
- device.model
- device.platform
- device.uuid
- device.version
## device.cordova
Get the version of Cordova running on the device.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
## device.model
The `device.model` returns the name of the device's model or
product. The value is set by the device manufacturer and may be
different across versions of the same product.
### Supported Platforms
- Android
- BlackBerry 10
- Browser
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
### Quick Example
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models
//
var model = device.model;
### Android Quirks
- Gets the [product name](http://developer.android.com/reference/android/os/Build.html#PRODUCT) instead of the [model name](http://developer.android.com/reference/android/os/Build.html#MODEL), which is often the production code name. For example, the Nexus One returns `Passion`, and Motorola Droid returns `voles`.
### Tizen Quirks
- Returns the device model assigned by the vendor, for example, `TIZEN`
### Windows Phone 7 and 8 Quirks
- Returns the device model specified by the manufacturer. For example, the Samsung Focus returns `SGH-i917`.
## device.platform
Get the device's operating system name.
var string = device.platform;
### Supported Platforms
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
### Quick Example
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 Quirks
Windows Phone 7 devices report the platform as `WinCE`.
### Windows Phone 8 Quirks
Windows Phone 8 devices report the platform as `Win32NT`.
## device.uuid
Get the device's Universally Unique Identifier ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)).
var string = device.uuid;
### Description
The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model.
### Supported Platforms
- Android
- BlackBerry 10
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
### Quick Example
// Android: Returns a random 64-bit integer (as a string, again!)
// The integer is generated on the device's first boot
//
// BlackBerry: Returns the PIN number of the device
// This is a nine-digit unique integer (as a string, though!)
//
// iPhone: (Paraphrased from the UIDevice Class documentation)
// Returns the [UIDevice identifierForVendor] UUID which is unique and the same for all apps installed by the same vendor. However the UUID can be different if the user deletes all apps from the vendor and then reinstalls it. Please see https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/#//apple_ref/occ/instp/UIDevice/identifierForVendor
// Windows Phone 7 : Returns a hash of device+current user,
// if the user is not defined, a guid is generated and will persist until the app is uninstalled
// Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number
// unique to every GSM and UMTS mobile phone.
var deviceID = device.uuid;
### iOS Quirk
The `uuid` on iOS uses the identifierForVendor property. It is unique to the device across the same vendor, but will be different for different vendors and will change if all apps from the vendor are deleted and then reinstalled.
See https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/#//apple_ref/occ/instp/UIDevice/identifierForVendor
The UUID will be the same if app is restored from a backup or iCloud as it is saved in preferences. Users using older versions of this plugin will still receive the same previous UUID generated by another means as it will be retrieved from preferences.
### Windows Phone 7 and 8 Quirks
The `uuid` for Windows Phone 7 requires the permission
`ID_CAP_IDENTITY_DEVICE`. Microsoft will likely deprecate this
property soon. If the capability is not available, the application
generates a persistent guid that is maintained for the duration of the
application's installation on the device.
## device.version
Get the operating system version.
var string = device.version;
### Supported Platforms
- Android 2.1+
- BlackBerry 10
- Browser
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
### Quick Example
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-device-motion
This plugin provides access to the device's accelerometer. The accelerometer is
a motion sensor that detects the change (_delta_) in movement relative to the
current device orientation, in three dimensions along the _x_, _y_, and _z_
axis.
Access is via a global `navigator.accelerometer` object.
Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.accelerometer);
}
## Installation
cordova plugin add cordova-plugin-device-motion
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 8
- Windows
## Methods
- navigator.accelerometer.getCurrentAcceleration
- navigator.accelerometer.watchAcceleration
- navigator.accelerometer.clearWatch
## Objects
- Acceleration
## navigator.accelerometer.getCurrentAcceleration
Get the current acceleration along the _x_, _y_, and _z_ axes.
These acceleration values are returned to the `accelerometerSuccess`
callback function.
navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);
### Example
function onSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
};
function onError() {
alert('onError!');
};
navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);
### Browser Quirks
Values for X, Y, Z motion are all randomly generated in order to simulate the accelerometer.
### iOS Quirks
- iOS doesn't recognize the concept of getting the current acceleration at any given point.
- You must watch the acceleration and capture the data at given time intervals.
- Thus, the `getCurrentAcceleration` function yields the last value reported from a `watchAccelerometer` call.
## navigator.accelerometer.watchAcceleration
Retrieves the device's current `Acceleration` at a regular interval, executing
the `accelerometerSuccess` callback function each time. Specify the interval in
milliseconds via the `acceleratorOptions` object's `frequency` parameter.
The returned watch ID references the accelerometer's watch interval,
and can be used with `navigator.accelerometer.clearWatch` to stop watching the
accelerometer.
var watchID = navigator.accelerometer.watchAcceleration(accelerometerSuccess,
accelerometerError,
accelerometerOptions);
- __accelerometerOptions__: An object with the following optional keys:
- __period__: requested period of calls to accelerometerSuccess with acceleration data in Milliseconds. _(Number)_ (Default: 10000)
### Example
function onSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
};
function onError() {
alert('onError!');
};
var options = { frequency: 3000 }; // Update every 3 seconds
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
### iOS Quirks
The API calls the success callback function at the interval requested,
but restricts the range of requests to the device between 40ms and
1000ms. For example, if you request an interval of 3 seconds,
(3000ms), the API requests data from the device every 1 second, but
only executes the success callback every 3 seconds.
## navigator.accelerometer.clearWatch
Stop watching the `Acceleration` referenced by the `watchID` parameter.
navigator.accelerometer.clearWatch(watchID);
- __watchID__: The ID returned by `navigator.accelerometer.watchAcceleration`.
### Example
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
// ... later on ...
navigator.accelerometer.clearWatch(watchID);
## Acceleration
Contains `Accelerometer` data captured at a specific point in time.
Acceleration values include the effect of gravity (9.81 m/s^2), so that when a
device lies flat and facing up, _x_, _y_, and _z_ values returned should be
`0`, `0`, and `9.81`.
### Properties
- __x__: Amount of acceleration on the x-axis. (in m/s^2) _(Number)_
- __y__: Amount of acceleration on the y-axis. (in m/s^2) _(Number)_
- __z__: Amount of acceleration on the z-axis. (in m/s^2) _(Number)_
- __timestamp__: Creation timestamp in milliseconds. _(DOMTimeStamp)_
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-device-orientation
This plugin provides access to the device's compass. The compass is a sensor
that detects the direction or heading that the device is pointed, typically
from the top of the device. It measures the heading in degrees from 0 to
359.99, where 0 is north.
Access is via a global `navigator.compass` object.
Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.compass);
}
## Installation
cordova plugin add cordova-plugin-device-orientation
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8 (if available in hardware)
- Windows 8
## Methods
- navigator.compass.getCurrentHeading
- navigator.compass.watchHeading
- navigator.compass.clearWatch
## navigator.compass.getCurrentHeading
Get the current compass heading. The compass heading is returned via a `CompassHeading`
object using the `compassSuccess` callback function.
navigator.compass.getCurrentHeading(compassSuccess, compassError);
### Example
function onSuccess(heading) {
alert('Heading: ' + heading.magneticHeading);
};
function onError(error) {
alert('CompassError: ' + error.code);
};
navigator.compass.getCurrentHeading(onSuccess, onError);
## navigator.compass.watchHeading
Gets the device's current heading at a regular interval. Each time the heading
is retrieved, the `headingSuccess` callback function is executed.
The returned watch ID references the compass watch interval. The watch
ID can be used with `navigator.compass.clearWatch` to stop watching the navigator.compass.
var watchID = navigator.compass.watchHeading(compassSuccess, compassError, [compassOptions]);
`compassOptions` may contain the following keys:
- __frequency__: How often to retrieve the compass heading in milliseconds. _(Number)_ (Default: 100)
- __filter__: The change in degrees required to initiate a watchHeading success callback. When this value is set, __frequency__ is ignored. _(Number)_
### Example
function onSuccess(heading) {
var element = document.getElementById('heading');
element.innerHTML = 'Heading: ' + heading.magneticHeading;
};
function onError(compassError) {
alert('Compass error: ' + compassError.code);
};
var options = {
frequency: 3000
}; // Update every 3 seconds
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
### Browser Quirks
Values for current heading are randomly generated in order to simulate the compass.
### iOS Quirks
Only one `watchHeading` can be in effect at one time in iOS. If a
`watchHeading` uses a filter, calling `getCurrentHeading` or
`watchHeading` uses the existing filter value to specify heading
changes. Watching heading changes with a filter is more efficient than
with time intervals.
### Amazon Fire OS Quirks
- `filter` is not supported.
### Android Quirks
- No support for `filter`.
### Firefox OS Quirks
- No support for `filter`.
### Tizen Quirks
- No support for `filter`.
### Windows Phone 7 and 8 Quirks
- No support for `filter`.
## navigator.compass.clearWatch
Stop watching the compass referenced by the watch ID parameter.
navigator.compass.clearWatch(watchID);
- __watchID__: The ID returned by `navigator.compass.watchHeading`.
### Example
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
// ... later on ...
navigator.compass.clearWatch(watchID);
## CompassHeading
A `CompassHeading` object is returned to the `compassSuccess` callback function.
### Properties
- __magneticHeading__: The heading in degrees from 0-359.99 at a single moment in time. _(Number)_
- __trueHeading__: The heading relative to the geographic North Pole in degrees 0-359.99 at a single moment in time. A negative value indicates that the true heading can't be determined. _(Number)_
- __headingAccuracy__: The deviation in degrees between the reported heading and the true heading. _(Number)_
- __timestamp__: The time at which this heading was determined. _(milliseconds)_
### Amazon Fire OS Quirks
- `trueHeading` is not supported, but reports the same value as `magneticHeading`
- `headingAccuracy` is always 0 because there is no difference between the `magneticHeading` and `trueHeading`
### Android Quirks
- The `trueHeading` property is not supported, but reports the same value as `magneticHeading`.
- The `headingAccuracy` property is always 0 because there is no difference between the `magneticHeading` and `trueHeading`.
### Firefox OS Quirks
- The `trueHeading` property is not supported, but reports the same value as `magneticHeading`.
- The `headingAccuracy` property is always 0 because there is no difference between the `magneticHeading` and `trueHeading`.
### iOS Quirks
- The `trueHeading` property is only returned for location services enabled via `navigator.geolocation.watchLocation()`.
- For iOS 4 devices and above, heading factors in the device's current orientation, and does not reference its absolute position, for apps that supports that orientation.
## CompassError
A `CompassError` object is returned to the `compassError` callback function when an error occurs.
### Properties
- __code__: One of the predefined error codes listed below.
### Constants
- `CompassError.COMPASS_INTERNAL_ERR`
- `CompassError.COMPASS_NOT_SUPPORTED`
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
This plugin provides access to some native dialog UI elements
via a global `navigator.notification` object.
Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Installation
cordova plugin add cordova-plugin-dialogs
## Methods
- `navigator.notification.alert`
- `navigator.notification.confirm`
- `navigator.notification.prompt`
- `navigator.notification.beep`
## navigator.notification.alert
Shows a custom alert or dialog box. Most Cordova implementations use a native
dialog box for this feature, but some platforms use the browser's `alert`
function, which is typically less customizable.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
- __message__: Dialog message. _(String)_
- __alertCallback__: Callback to invoke when alert dialog is dismissed. _(Function)_
- __title__: Dialog title. _(String)_ (Optional, defaults to `Alert`)
- __buttonName__: Button name. _(String)_ (Optional, defaults to `OK`)
### Example
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows
### Windows Phone 7 and 8 Quirks
- There is no built-in browser alert, but you can bind one as follows to call `alert()` in the global scope:
window.alert = navigator.notification.alert;
- Both `alert` and `confirm` are non-blocking calls, results of which are only available asynchronously.
### Firefox OS Quirks:
Both native-blocking `window.alert()` and non-blocking `navigator.notification.alert()` are available.
### BlackBerry 10 Quirks
`navigator.notification.alert('text', callback, 'title', 'text')` callback parameter is passed the number 1.
## navigator.notification.confirm
Displays a customizable confirmation dialog box.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
- __message__: Dialog message. _(String)_
- __confirmCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_
- __title__: Dialog title. _(String)_ (Optional, defaults to `Confirm`)
- __buttonLabels__: Array of strings specifying button labels. _(Array)_ (Optional, defaults to [`OK,Cancel`])
### confirmCallback
The `confirmCallback` executes when the user presses one of the
buttons in the confirmation dialog box.
The callback takes the argument `buttonIndex` _(Number)_, which is the
index of the pressed button. Note that the index uses one-based
indexing, so the value is `1`, `2`, `3`, etc.
### Example
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows
### Windows Phone 7 and 8 Quirks
- There is no built-in browser function for `window.confirm`, but you can bind it by assigning:
window.confirm = navigator.notification.confirm;
- Calls to `alert` and `confirm` are non-blocking, so the result is only available asynchronously.
### Windows Quirks
- On Windows8/8.1 it is not possible to add more than three buttons to MessageDialog instance.
- On Windows Phone 8.1 it's not possible to show dialog with more than two buttons.
### Firefox OS Quirks:
Both native-blocking `window.confirm()` and non-blocking `navigator.notification.confirm()` are available.
## navigator.notification.prompt
Displays a native dialog box that is more customizable than the browser's `prompt` function.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
- __message__: Dialog message. _(String)_
- __promptCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_
- __title__: Dialog title _(String)_ (Optional, defaults to `Prompt`)
- __buttonLabels__: Array of strings specifying button labels _(Array)_ (Optional, defaults to `["OK","Cancel"]`)
- __defaultText__: Default textbox input value (`String`) (Optional, Default: empty string)
### promptCallback
The `promptCallback` executes when the user presses one of the buttons
in the prompt dialog box. The `results` object passed to the callback
contains the following properties:
- __buttonIndex__: The index of the pressed button. _(Number)_ Note that the index uses one-based indexing, so the value is `1`, `2`, `3`, etc.
- __input1__: The text entered in the prompt dialog box. _(String)_
### Example
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Supported Platforms
- Amazon Fire OS
- Android
- Firefox OS
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
### Android Quirks
- Android supports a maximum of three buttons, and ignores any more than that.
- On Android 3.0 and later, buttons are displayed in reverse order for devices that use the Holo theme.
### Windows Quirks
- On Windows prompt dialog is html-based due to lack of such native api.
### Firefox OS Quirks:
Both native-blocking `window.prompt()` and non-blocking `navigator.notification.prompt()` are available.
## navigator.notification.beep
The device plays a beep sound.
navigator.notification.beep(times);
- __times__: The number of times to repeat the beep. _(Number)_
### Example
// Beep twice!
navigator.notification.beep(2);
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
### Amazon Fire OS Quirks
- Amazon Fire OS plays the default __Notification Sound__ specified under the __Settings/Display & Sound__ panel.
### Android Quirks
- Android plays the default __Notification ringtone__ specified under the __Settings/Sound & Display__ panel.
### Windows Phone 7 and 8 Quirks
- Relies on a generic beep file from the Cordova distribution.
### Tizen Quirks
- Tizen implements beeps by playing an audio file via the media API.
- The beep file must be short, must be located in a `sounds` subdirectory of the application's root directory, and must be named `beep.wav`.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-file
This plugin implements a File API allowing read/write access to files residing on the device.
This plugin is based on several specs, including :
The HTML5 File API
[http://www.w3.org/TR/FileAPI/](http://www.w3.org/TR/FileAPI/)
The (now-defunct) Directories and System extensions
Latest:
[http://www.w3.org/TR/2012/WD-file-system-api-20120417/](http://www.w3.org/TR/2012/WD-file-system-api-20120417/)
Although most of the plugin code was written when an earlier spec was current:
[http://www.w3.org/TR/2011/WD-file-system-api-20110419/](http://www.w3.org/TR/2011/WD-file-system-api-20110419/)
It also implements the FileWriter spec :
[http://dev.w3.org/2009/dap/file-system/file-writer.html](http://dev.w3.org/2009/dap/file-system/file-writer.html)
For usage, please refer to HTML5 Rocks' excellent [FileSystem article.](http://www.html5rocks.com/en/tutorials/file/filesystem/)
For an overview of other storage options, refer to Cordova's
[storage guide](http://cordova.apache.org/docs/en/edge/cordova_storage_storage.md.html).
This plugin defines global `cordova.file` object.
Although in the global scope, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(cordova.file);
}
## Installation
cordova plugin add cordova-plugin-file
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- OS X
- Windows Phone 7 and 8*
- Windows 8*
- Windows*
- Browser
\* _These platforms do not support `FileReader.readAsArrayBuffer` nor `FileWriter.write(blob)`._
## Where to Store Files
As of v1.2.0, URLs to important file-system directories are provided.
Each URL is in the form _file:///path/to/spot/_, and can be converted to a
`DirectoryEntry` using `window.resolveLocalFileSystemURL()`.
* `cordova.file.applicationDirectory` - Read-only directory where the application
is installed. (_iOS_, _Android_, _BlackBerry 10_, _OSX_)
* `cordova.file.applicationStorageDirectory` - Root directory of the application's
sandbox; on iOS this location is read-only (but specific subdirectories [like
`/Documents`] are read-write). All data contained within is private to the app. (
_iOS_, _Android_, _BlackBerry 10_, _OSX_)
* `cordova.file.dataDirectory` - Persistent and private data storage within the
application's sandbox using internal memory (on Android, if you need to use
external memory, use `.externalDataDirectory`). On iOS, this directory is not
synced with iCloud (use `.syncedDataDirectory`). (_iOS_, _Android_, _BlackBerry 10_)
* `cordova.file.cacheDirectory` - Directory for cached data files or any files
that your app can re-create easily. The OS may delete these files when the device
runs low on storage, nevertheless, apps should not rely on the OS to delete files
in here. (_iOS_, _Android_, _BlackBerry 10_, _OSX_)
* `cordova.file.externalApplicationStorageDirectory` - Application space on
external storage. (_Android_)
* `cordova.file.externalDataDirectory` - Where to put app-specific data files on
external storage. (_Android_)
* `cordova.file.externalCacheDirectory` - Application cache on external storage.
(_Android_)
* `cordova.file.externalRootDirectory` - External storage (SD card) root. (_Android_, _BlackBerry 10_)
* `cordova.file.tempDirectory` - Temp directory that the OS can clear at will. Do not
rely on the OS to clear this directory; your app should always remove files as
applicable. (_iOS_, _OSX_)
* `cordova.file.syncedDataDirectory` - Holds app-specific files that should be synced
(e.g. to iCloud). (_iOS_)
* `cordova.file.documentsDirectory` - Files private to the app, but that are meaningful
to other application (e.g. Office files). Note that for _OSX_ this is the user's `~/Documents` directory. (_iOS_, _OSX_)
* `cordova.file.sharedDirectory` - Files globally available to all applications (_BlackBerry 10_)
## File System Layouts
Although technically an implementation detail, it can be very useful to know how
the `cordova.file.*` properties map to physical paths on a real device.
### iOS File System Layout
| Device Path | `cordova.file.*` | `iosExtraFileSystems` | r/w? | persistent? | OS clears | sync | private |
|:-----------------------------------------------|:----------------------------|:----------------------|:----:|:-----------:|:---------:|:----:|:-------:|
| `/var/mobile/Applications/<UUID>/` | applicationStorageDirectory | - | r | N/A | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`appname.app/` | applicationDirectory | bundle | r | N/A | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`www/` | - | - | r | N/A | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`Documents/` | documentsDirectory | documents | r/w | Yes | No | Yes | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | - | documents-nosync | r/w | Yes | No | No | Yes |
| &nbsp;&nbsp;&nbsp;`Library` | - | library | r/w | Yes | No | Yes? | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`NoCloud/` | dataDirectory | library-nosync | r/w | Yes | No | No | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Cloud/` | syncedDataDirectory | - | r/w | Yes | No | Yes | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Caches/` | cacheDirectory | cache | r/w | Yes* | Yes\*\*\*| No | Yes |
| &nbsp;&nbsp;&nbsp;`tmp/` | tempDirectory | - | r/w | No\*\* | Yes\*\*\*| No | Yes |
\* Files persist across app restarts and upgrades, but this directory can
be cleared whenever the OS desires. Your app should be able to recreate any
content that might be deleted.
\*\* Files may persist across app restarts, but do not rely on this behavior. Files
are not guaranteed to persist across updates. Your app should remove files from
this directory when it is applicable, as the OS does not guarantee when (or even
if) these files are removed.
\*\*\* The OS may clear the contents of this directory whenever it feels it is
necessary, but do not rely on this. You should clear this directory as
appropriate for your application.
### Android File System Layout
| Device Path | `cordova.file.*` | `AndroidExtraFileSystems` | r/w? | persistent? | OS clears | private |
|:------------------------------------------------|:----------------------------|:--------------------------|:----:|:-----------:|:---------:|:-------:|
| `file:///android_asset/` | applicationDirectory | | r | N/A | N/A | Yes |
| `/data/data/<app-id>/` | applicationStorageDirectory | - | r/w | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`cache` | cacheDirectory | cache | r/w | Yes | Yes\* | Yes |
| &nbsp;&nbsp;&nbsp;`files` | dataDirectory | files | r/w | Yes | No | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`Documents` | | documents | r/w | Yes | No | Yes |
| `<sdcard>/` | externalRootDirectory | sdcard | r/w | Yes | No | No |
| &nbsp;&nbsp;&nbsp;`Android/data/<app-id>/` | externalApplicationStorageDirectory | - | r/w | Yes | No | No |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`cache` | externalCacheDirectry | cache-external | r/w | Yes | No\*\*| No |
| &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`files` | externalDataDirectory | files-external | r/w | Yes | No | No |
\* The OS may periodically clear this directory, but do not rely on this behavior. Clear
the contents of this directory as appropriate for your application. Should a user
purge the cache manually, the contents of this directory are removed.
\*\* The OS does not clear this directory automatically; you are responsible for managing
the contents yourself. Should the user purge the cache manually, the contents of the
directory are removed.
**Note**: If external storage can't be mounted, the `cordova.file.external*`
properties are `null`.
### BlackBerry 10 File System Layout
| Device Path | `cordova.file.*` | r/w? | persistent? | OS clears | private |
|:-------------------------------------------------------------|:----------------------------|:----:|:-----------:|:---------:|:-------:|
| `file:///accounts/1000/appdata/<app id>/` | applicationStorageDirectory | r | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`app/native` | applicationDirectory | r | N/A | N/A | Yes |
| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/temporary/local__0` | cacheDirectory | r/w | No | Yes | Yes |
| &nbsp;&nbsp;&nbsp;`data/webviews/webfs/persistent/local__0` | dataDirectory | r/w | Yes | No | Yes |
| `file:///accounts/1000/removable/sdcard` | externalRemovableDirectory | r/w | Yes | No | No |
| `file:///accounts/1000/shared` | sharedDirectory | r/w | Yes | No | No |
*Note*: When application is deployed to work perimeter, all paths are relative to /accounts/1000-enterprise.
### OS X File System Layout
| Device Path | `cordova.file.*` | `iosExtraFileSystems` | r/w? | OS clears | private |
|:-------------------------------------------------|:----------------------------|:----------------------|:----:|:---------:|:-------:|
| `/Applications/<appname>.app/` | - | bundle | r | N/A | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;`Content/Resources/` | applicationDirectory | - | r | N/A | Yes |
| `~/Library/Application Support/<bundle-id>/` | applicationStorageDirectory | - | r/w | No | Yes |
| &nbsp;&nbsp;&nbsp;&nbsp;`files/` | dataDirectory | - | r/w | No | Yes |
| `~/Documents/` | documentsDirectory | documents | r/w | No | No |
| `~/Library/Caches/<bundle-id>/` | cacheDirectory | cache | r/w | No | Yes |
| `/tmp/` | tempDirectory | - | r/w | Yes\* | Yes |
| `/` | rootDirectory | root | r/w | No\*\* | No |
**Note**: This is the layout for non sandboxed applications. I you enable sandboxing, the `applicationStorageDirectory` will be below ` ~/Library/Containers/<bundle-id>/Data/Library/Application Support`.
\* Files persist across app restarts and upgrades, but this directory can
be cleared whenever the OS desires. Your app should be able to recreate any
content that might be deleted. You should clear this directory as
appropriate for your application.
\*\* Allows access to the entire file system. This is only available for non sandboxed apps.
## Android Quirks
### Android Persistent storage location
There are multiple valid locations to store persistent files on an Android
device. See [this page](http://developer.android.com/guide/topics/data/data-storage.html)
for an extensive discussion of the various possibilities.
Previous versions of the plugin would choose the location of the temporary and
persistent files on startup, based on whether the device claimed that the SD
Card (or equivalent storage partition) was mounted. If the SD Card was mounted,
or if a large internal storage partition was available (such as on Nexus
devices,) then the persistent files would be stored in the root of that space.
This meant that all Cordova apps could see all of the files available on the
card.
If the SD card was not available, then previous versions would store data under
`/data/data/<packageId>`, which isolates apps from each other, but may still
cause data to be shared between users.
It is now possible to choose whether to store files in the internal file
storage location, or using the previous logic, with a preference in your
application's `config.xml` file. To do this, add one of these two lines to
`config.xml`:
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
Without this line, the File plugin will use `Internal` as the default. If
a preference tag is present, and is not one of these values, the application
will not start.
If your application has previously been shipped to users, using an older (pre-
3.0.0) version of this plugin, and has stored files in the persistent filesystem,
then you should set the preference to `Compatibility` if your config.xml does not specify a location for the persistent filesystem. Switching the location to
"Internal" would mean that existing users who upgrade their application may be
unable to access their previously-stored files, depending on their device.
If your application is new, or has never previously stored files in the
persistent filesystem, then the `Internal` setting is generally recommended.
### Slow recursive operations for /android_asset
Listing asset directories is really slow on Android. You can speed it up though, by
adding `src/android/build-extras.gradle` to the root of your android project (also
requires cordova-android@4.0.0 or greater).
## iOS Quirks
- `cordova.file.applicationStorageDirectory` is read-only; attempting to store
files within the root directory will fail. Use one of the other `cordova.file.*`
properties defined for iOS (only `applicationDirectory` and `applicationStorageDirectory` are
read-only).
- `FileReader.readAsText(blob, encoding)`
- The `encoding` parameter is not supported, and UTF-8 encoding is always in effect.
### iOS Persistent storage location
There are two valid locations to store persistent files on an iOS device: the
Documents directory and the Library directory. Previous versions of the plugin
only ever stored persistent files in the Documents directory. This had the
side-effect of making all of an application's files visible in iTunes, which
was often unintended, especially for applications which handle lots of small
files, rather than producing complete documents for export, which is the
intended purpose of the directory.
It is now possible to choose whether to store files in the documents or library
directory, with a preference in your application's `config.xml` file. To do this,
add one of these two lines to `config.xml`:
<preference name="iosPersistentFileLocation" value="Library" />
<preference name="iosPersistentFileLocation" value="Compatibility" />
Without this line, the File plugin will use `Compatibility` as the default. If
a preference tag is present, and is not one of these values, the application
will not start.
If your application has previously been shipped to users, using an older (pre-
1.0) version of this plugin, and has stored files in the persistent filesystem,
then you should set the preference to `Compatibility`. Switching the location to
`Library` would mean that existing users who upgrade their application would be
unable to access their previously-stored files.
If your application is new, or has never previously stored files in the
persistent filesystem, then the `Library` setting is generally recommended.
## Firefox OS Quirks
The File System API is not natively supported by Firefox OS and is implemented
as a shim on top of indexedDB.
* Does not fail when removing non-empty directories
* Does not support metadata for directories
* Methods `copyTo` and `moveTo` do not support directories
The following data paths are supported:
* `applicationDirectory` - Uses `xhr` to get local files that are packaged with the app.
* `dataDirectory` - For persistent app-specific data files.
* `cacheDirectory` - Cached files that should survive app restarts (Apps should not rely
on the OS to delete files in here).
## Browser Quirks
### Common quirks and remarks
- Each browser uses its own sandboxed filesystem. IE and Firefox use IndexedDB as a base.
All browsers use forward slash as directory separator in a path.
- Directory entries have to be created successively.
For example, the call `fs.root.getDirectory('dir1/dir2', {create:true}, successCallback, errorCallback)`
will fail if dir1 did not exist.
- The plugin requests user permission to use persistent storage at the application first start.
- Plugin supports `cdvfile://localhost` (local resources) only. I.e. external resources are not supported via `cdvfile`.
- The plugin does not follow ["File System API 8.3 Naming restrictions"](http://www.w3.org/TR/2011/WD-file-system-api-20110419/#naming-restrictions).
- Blob and File' `close` function is not supported.
- `FileSaver` and `BlobBuilder` are not supported by this plugin and don't have stubs.
- The plugin does not support `requestAllFileSystems`. This function is also missing in the specifications.
- Entries in directory will not be removed if you use `create: true` flag for existing directory.
- Files created via constructor are not supported. You should use entry.file method instead.
- Each browser uses its own form for blob URL references.
- `readAsDataURL` function is supported, but the mediatype in Chrome depends on entry name extension,
mediatype in IE is always empty (which is the same as `text-plain` according the specification),
the mediatype in Firefox is always `application/octet-stream`.
For example, if the content is `abcdefg` then Firefox returns `data:application/octet-stream;base64,YWJjZGVmZw==`,
IE returns `data:;base64,YWJjZGVmZw==`, Chrome returns `data:<mediatype depending on extension of entry name>;base64,YWJjZGVmZw==`.
- `toInternalURL` returns the path in the form `file:///persistent/path/to/entry` (Firefox, IE).
Chrome returns the path in the form `cdvfile://localhost/persistent/file`.
### Chrome quirks
- Chrome filesystem is not immediately ready after device ready event. As a workaround you can subscribe to `filePluginIsReady` event.
Example:
```javascript
window.addEventListener('filePluginIsReady', function(){ console.log('File plugin is ready');}, false);
```
You can use `window.isFilePluginReadyRaised` function to check whether event was already raised.
- window.requestFileSystem TEMPORARY and PERSISTENT filesystem quotas are not limited in Chrome.
- To increase persistent storage in Chrome you need to call `window.initPersistentFileSystem` method. Persistent storage quota is 5 MB by default.
- Chrome requires `--allow-file-access-from-files` run argument to support API via `file:///` protocol.
- `File` object will be not changed if you use flag `{create:true}` when getting an existing `Entry`.
- events `cancelable` property is set to true in Chrome. This is contrary to the [specification](http://dev.w3.org/2009/dap/file-system/file-writer.html).
- `toURL` function in Chrome returns `filesystem:`-prefixed path depending on application host.
For example, `filesystem:file:///persistent/somefile.txt`, `filesystem:http://localhost:8080/persistent/somefile.txt`.
- `toURL` function result does not contain trailing slash in case of directory entry.
Chrome resolves directories with slash-trailed urls correctly though.
- `resolveLocalFileSystemURL` method requires the inbound `url` to have `filesystem` prefix. For example, `url` parameter for `resolveLocalFileSystemURL`
should be in the form `filesystem:file:///persistent/somefile.txt` as opposed to the form `file:///persistent/somefile.txt` in Android.
- Deprecated `toNativeURL` function is not supported and does not have a stub.
- `setMetadata` function is not stated in the specifications and not supported.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of SYNTAX_ERR(code: 8) on requesting of a non-existant filesystem.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of PATH_EXISTS_ERR(code: 12) on trying to exclusively create a file or directory, which already exists.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NO_MODIFICATION_ALLOWED_ERR(code: 6) on trying to call removeRecursively on the root file system.
- INVALID_MODIFICATION_ERR (code: 9) is thrown instead of NOT_FOUND_ERR(code: 1) on trying to moveTo directory that does not exist.
### IndexedDB-based impl quirks (Firefox and IE)
- `.` and `..` are not supported.
- IE does not support `file:///`-mode; only hosted mode is supported (http://localhost:xxxx).
- Firefox filesystem size is not limited but each 50MB extension will request a user permission.
IE10 allows up to 10mb of combined AppCache and IndexedDB used in implementation of filesystem without prompting,
once you hit that level you will be asked if you want to allow it to be increased up to a max of 250mb per site.
So `size` parameter for `requestFileSystem` function does not affect filesystem in Firefox and IE.
- `readAsBinaryString` function is not stated in the Specs and not supported in IE and does not have a stub.
- `file.type` is always null.
- You should not create entry using DirectoryEntry instance callback result which was deleted.
Otherwise, you will get a 'hanging entry'.
- Before you can read a file, which was just written you need to get a new instance of this file.
- `setMetadata` function, which is not stated in the Specs supports `modificationTime` field change only.
- `copyTo` and `moveTo` functions do not support directories.
- Directories metadata is not supported.
- Both Entry.remove and directoryEntry.removeRecursively don't fail when removing
non-empty directories - directories being removed are cleaned along with contents instead.
- `abort` and `truncate` functions are not supported.
- progress events are not fired. For example, this handler will be not executed:
```javascript
writer.onprogress = function() { /*commands*/ };
```
## Upgrading Notes
In v1.0.0 of this plugin, the `FileEntry` and `DirectoryEntry` structures have changed,
to be more in line with the published specification.
Previous (pre-1.0.0) versions of the plugin stored the device-absolute-file-location
in the `fullPath` property of `Entry` objects. These paths would typically look like
/var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
/storage/emulated/0/path/to/file (Android)
These paths were also returned by the `toURL()` method of the `Entry` objects.
With v1.0.0, the `fullPath` attribute is the path to the file, _relative to the root of
the HTML filesystem_. So, the above paths would now both be represented by a `FileEntry`
object with a `fullPath` of
/path/to/file
If your application works with device-absolute-paths, and you previously retrieved those
paths through the `fullPath` property of `Entry` objects, then you should update your code
to use `entry.toURL()` instead.
For backwards compatibility, the `resolveLocalFileSystemURL()` method will accept a
device-absolute-path, and will return an `Entry` object corresponding to it, as long as that
file exists within either the `TEMPORARY` or `PERSISTENT` filesystems.
This has particularly been an issue with the File-Transfer plugin, which previously used
device-absolute-paths (and can still accept them). It has been updated to work correctly
with FileSystem URLs, so replacing `entry.fullPath` with `entry.toURL()` should resolve any
issues getting that plugin to work with files on the device.
In v1.1.0 the return value of `toURL()` was changed (see [CB-6394] (https://issues.apache.org/jira/browse/CB-6394))
to return an absolute 'file://' URL. wherever possible. To ensure a 'cdvfile:'-URL you can use `toInternalURL()` now.
This method will now return filesystem URLs of the form
cdvfile://localhost/persistent/path/to/file
which can be used to identify the file uniquely.
## cdvfile protocol
**Purpose**
`cdvfile://localhost/persistent|temporary|another-fs-root*/path/to/file` can be used for platform-independent file paths.
cdvfile paths are supported by core plugins - for example you can download an mp3 file to cdvfile-path via `cordova-plugin-file-transfer` and play it via `cordova-plugin-media`.
__*Note__: See [Where to Store Files](#where-to-store-files), [File System Layouts](#file-system-layouts) and [Configuring the Plugin](#configuring-the-plugin-optional) for more details about available fs roots.
To use `cdvfile` as a tag' `src` you can convert it to native path via `toURL()` method of the resolved fileEntry, which you can get via `resolveLocalFileSystemURL` - see examples below.
You can also use `cdvfile://` paths directly in the DOM, for example:
```HTML
<img src="cdvfile://localhost/persistent/img/logo.png" />
```
__*Note__: This method requires following Content Security rules updates:
* Add `cdvfile:` scheme to `Content-Security-Policy` meta tag of the index page, e.g.:
- `<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: `**cdvfile:**` https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">`
* Add `<access origin="cdvfile://*" />` to `config.xml`.
**Converting cdvfile:// to native path**
```javascript
resolveLocalFileSystemURL('cdvfile://localhost/temporary/path/to/file.mp4', function(entry) {
var nativePath = entry.toURL();
console.log('Native URI: ' + nativePath);
document.getElementById('video').src = nativePath;
```
**Converting native path to cdvfile://**
```javascript
resolveLocalFileSystemURL(nativePath, function(entry) {
console.log('cdvfile URI: ' + entry.toInternalURL());
```
**Using cdvfile in core plugins**
```javascript
fileTransfer.download(uri, 'cdvfile://localhost/temporary/path/to/file.mp3', function (entry) { ...
```
```javascript
var my_media = new Media('cdvfile://localhost/temporary/path/to/file.mp3', ...);
my_media.play();
```
## List of Error Codes and Meanings
When an error is thrown, one of the following codes will be used.
| Code | Constant |
|-----:|:------------------------------|
| 1 | `NOT_FOUND_ERR` |
| 2 | `SECURITY_ERR` |
| 3 | `ABORT_ERR` |
| 4 | `NOT_READABLE_ERR` |
| 5 | `ENCODING_ERR` |
| 6 | `NO_MODIFICATION_ALLOWED_ERR` |
| 7 | `INVALID_STATE_ERR` |
| 8 | `SYNTAX_ERR` |
| 9 | `INVALID_MODIFICATION_ERR` |
| 10 | `QUOTA_EXCEEDED_ERR` |
| 11 | `TYPE_MISMATCH_ERR` |
| 12 | `PATH_EXISTS_ERR` |
## Configuring the Plugin (Optional)
The set of available filesystems can be configured per-platform. Both iOS and
Android recognize a <preference> tag in `config.xml` which names the
filesystems to be installed. By default, all file-system roots are enabled.
<preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" />
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,root" />
### Android
* `files`: The application's internal file storage directory
* `files-external`: The application's external file storage directory
* `sdcard`: The global external file storage directory (this is the root of the SD card, if one is installed). You must have the `android.permission.WRITE_EXTERNAL_STORAGE` permission to use this.
* `cache`: The application's internal cache directory
* `cache-external`: The application's external cache directory
* `root`: The entire device filesystem
Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
### iOS
* `library`: The application's Library directory
* `documents`: The application's Documents directory
* `cache`: The application's Cache directory
* `bundle`: The application's bundle; the location of the app itself on disk (read-only)
* `root`: The entire device filesystem
By default, the library and documents directories can be synced to iCloud. You can also request two additional filesystems, `library-nosync` and `documents-nosync`, which represent a special non-synced directory within the `/Library` or `/Documents` filesystem.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-file-transfer
This plugin allows you to upload and download files.
This plugin defines global `FileTransfer`, `FileUploadOptions` Constructors.
Although in the global scope, they are not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(FileTransfer);
}
## Installation
cordova plugin add cordova-plugin-file-transfer
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS**
- iOS
- Windows Phone 7 and 8*
- Windows 8
- Windows
\* _Do not support `onprogress` nor `abort()`_
\** _Do not support `onprogress`_
# FileTransfer
The `FileTransfer` object provides a way to upload files using an HTTP
multi-part POST or PUT request, and to download files as well.
## Properties
- __onprogress__: Called with a `ProgressEvent` whenever a new chunk of data is transferred. _(Function)_
## Methods
- __upload__: sends a file to a server.
- __download__: downloads a file from server.
- __abort__: Aborts an in-progress transfer.
## upload
__Parameters__:
- __fileURL__: Filesystem URL representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device. (See [Backwards Compatibility Notes] below)
- __server__: URL of the server to receive the file, as encoded by `encodeURI()`.
- __successCallback__: A callback that is passed a `FileUploadResult` object. _(Function)_
- __errorCallback__: A callback that executes if an error occurs retrieving the `FileUploadResult`. Invoked with a `FileTransferError` object. _(Function)_
- __options__: Optional parameters _(Object)_. Valid keys:
- __fileKey__: The name of the form element. Defaults to `file`. (DOMString)
- __fileName__: The file name to use when saving the file on the server. Defaults to `image.jpg`. (DOMString)
- __httpMethod__: The HTTP method to use - either `PUT` or `POST`. Defaults to `POST`. (DOMString)
- __mimeType__: The mime type of the data to upload. Defaults to `image/jpeg`. (DOMString)
- __params__: A set of optional key/value pairs to pass in the HTTP request. (Object)
- __chunkedMode__: Whether to upload the data in chunked streaming mode. Defaults to `true`. (Boolean)
- __headers__: A map of header name/header values. Use an array to specify more than one value. On iOS, FireOS, and Android, if a header named Content-Type is present, multipart form data will NOT be used. (Object)
- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. This is useful since Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS. _(boolean)_
### Example
// !! Assumes variable fileURL contains a valid URL to a text file on the device,
// for example, cdvfile://localhost/persistent/path/to/file.txt
var win = function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
### Example with Upload Headers and Progress Events (Android and iOS only)
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var uri = encodeURI("http://some.server.com/upload.php");
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType="text/plain";
var headers={'headerParam':'headerValue'};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
} else {
loadingStatus.increment();
}
};
ft.upload(fileURL, uri, win, fail, options);
## FileUploadResult
A `FileUploadResult` object is passed to the success callback of the
`FileTransfer` object's `upload()` method.
### Properties
- __bytesSent__: The number of bytes sent to the server as part of the upload. (long)
- __responseCode__: The HTTP response code returned by the server. (long)
- __response__: The HTTP response returned by the server. (DOMString)
- __headers__: The HTTP response headers by the server. (Object)
- Currently supported on iOS only.
### iOS Quirks
- Does not support `responseCode` or `bytesSent`.
### Browser Quirks
- __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest
## download
__Parameters__:
- __source__: URL of the server to download the file, as encoded by `encodeURI()`.
- __target__: Filesystem url representing the file on the device. For backwards compatibility, this can also be the full path of the file on the device. (See [Backwards Compatibility Notes] below)
- __successCallback__: A callback that is passed a `FileEntry` object. _(Function)_
- __errorCallback__: A callback that executes if an error occurs when retrieving the `FileEntry`. Invoked with a `FileTransferError` object. _(Function)_
- __trustAllHosts__: Optional parameter, defaults to `false`. If set to `true`, it accepts all security certificates. This is useful because Android rejects self-signed security certificates. Not recommended for production use. Supported on Android and iOS. _(boolean)_
- __options__: Optional parameters, currently only supports headers (such as Authorization (Basic Authentication), etc).
### Example
// !! Assumes variable fileURL contains a valid URL to a path on the device,
// for example, cdvfile://localhost/persistent/path/to/downloads/
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://some.server.com/download.php");
fileTransfer.download(
uri,
fileURL,
function(entry) {
console.log("download complete: " + entry.toURL());
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
### WP8 Quirks
- Download requests is being cached by native implementation. To avoid caching, pass `if-Modified-Since` header to download method.
### Browser Quirks
- __withCredentials__: _boolean_ that tells the browser to set the withCredentials flag on the XMLHttpRequest
## abort
Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.
### Example
// !! Assumes variable fileURL contains a valid URL to a text file on the device,
// for example, cdvfile://localhost/persistent/path/to/file.txt
var win = function(r) {
console.log("Should not be called.");
}
var fail = function(error) {
// error.code == FileTransferError.ABORT_ERR
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName="myphoto.jpg";
options.mimeType="image/jpeg";
var ft = new FileTransfer();
ft.upload(fileURL, encodeURI("http://some.server.com/upload.php"), win, fail, options);
ft.abort();
## FileTransferError
A `FileTransferError` object is passed to an error callback when an error occurs.
### Properties
- __code__: One of the predefined error codes listed below. (Number)
- __source__: URL to the source. (String)
- __target__: URL to the target. (String)
- __http_status__: HTTP status code. This attribute is only available when a response code is received from the HTTP connection. (Number)
- __body__ Response body. This attribute is only available when a response is received from the HTTP connection. (String)
- __exception__: Either e.getMessage or e.toString (String)
### Constants
- 1 = `FileTransferError.FILE_NOT_FOUND_ERR`
- 2 = `FileTransferError.INVALID_URL_ERR`
- 3 = `FileTransferError.CONNECTION_ERR`
- 4 = `FileTransferError.ABORT_ERR`
- 5 = `FileTransferError.NOT_MODIFIED_ERR`
## Backwards Compatibility Notes
Previous versions of this plugin would only accept device-absolute-file-paths as the source for uploads, or as the target for downloads. These paths would typically be of the form
/var/mobile/Applications/<application UUID>/Documents/path/to/file (iOS)
/storage/emulated/0/path/to/file (Android)
For backwards compatibility, these paths are still accepted, and if your application has recorded paths like these in persistent storage, then they can continue to be used.
These paths were previously exposed in the `fullPath` property of `FileEntry` and `DirectoryEntry` objects returned by the File plugin. New versions of the File plugin, however, no longer expose these paths to JavaScript.
If you are upgrading to a new (1.0.0 or newer) version of File, and you have previously been using `entry.fullPath` as arguments to `download()` or `upload()`, then you will need to change your code to use filesystem URLs instead.
`FileEntry.toURL()` and `DirectoryEntry.toURL()` return a filesystem URL of the form
cdvfile://localhost/persistent/path/to/file
which can be used in place of the absolute file path in both `download()` and `upload()` methods.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-geolocation
This plugin provides information about the device's location, such as
latitude and longitude. Common sources of location information include
Global Positioning System (GPS) and location inferred from network
signals such as IP address, RFID, WiFi and Bluetooth MAC addresses,
and GSM/CDMA cell IDs. There is no guarantee that the API returns the
device's actual location.
This API is based on the
[W3C Geolocation API Specification](http://dev.w3.org/geo/api/spec-source.html),
and only executes on devices that don't already provide an implementation.
__WARNING__: Collection and use of geolocation data
raises important privacy issues. Your app's privacy policy should
discuss how the app uses geolocation data, whether it is shared with
any other parties, and the level of precision of the data (for
example, coarse, fine, ZIP code level, etc.). Geolocation data is
generally considered sensitive because it can reveal user's
whereabouts and, if stored, the history of their travels.
Therefore, in addition to the app's privacy policy, you should
strongly consider providing a just-in-time notice before the app
accesses geolocation data (if the device operating system doesn't do
so already). That notice should provide the same information noted
above, as well as obtaining the user's permission (e.g., by presenting
choices for __OK__ and __No Thanks__). For more information, please
see the Privacy Guide.
This plugin defines a global `navigator.geolocation` object (for platforms
where it is otherwise missing).
Although the object is in the global scope, features provided by this plugin
are not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("navigator.geolocation works well");
}
## Installation
This requires cordova 5.0+ ( current stable 1.0.0 )
cordova plugin add cordova-plugin-geolocation
Older versions of cordova can still install via the deprecated id ( stale 0.3.12 )
cordova plugin add org.apache.cordova.geolocation
It is also possible to install via repo url directly ( unstable )
cordova plugin add https://github.com/apache/cordova-plugin-geolocation.git
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows
## Methods
- navigator.geolocation.getCurrentPosition
- navigator.geolocation.watchPosition
- navigator.geolocation.clearWatch
## Objects (Read-Only)
- Position
- PositionError
- Coordinates
## navigator.geolocation.getCurrentPosition
Returns the device's current position to the `geolocationSuccess`
callback with a `Position` object as the parameter. If there is an
error, the `geolocationError` callback is passed a
`PositionError` object.
navigator.geolocation.getCurrentPosition(geolocationSuccess,
[geolocationError],
[geolocationOptions]);
### Parameters
- __geolocationSuccess__: The callback that is passed the current position.
- __geolocationError__: _(Optional)_ The callback that executes if an error occurs.
- __geolocationOptions__: _(Optional)_ The geolocation options.
### Example
// onSuccess Callback
// This method accepts a Position object, which contains the
// current GPS coordinates
//
var onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
## navigator.geolocation.watchPosition
Returns the device's current position when a change in position is detected.
When the device retrieves a new location, the `geolocationSuccess`
callback executes with a `Position` object as the parameter. If
there is an error, the `geolocationError` callback executes with a
`PositionError` object as the parameter.
var watchId = navigator.geolocation.watchPosition(geolocationSuccess,
[geolocationError],
[geolocationOptions]);
### Parameters
- __geolocationSuccess__: The callback that is passed the current position.
- __geolocationError__: (Optional) The callback that executes if an error occurs.
- __geolocationOptions__: (Optional) The geolocation options.
### Returns
- __String__: returns a watch id that references the watch position interval. The watch id should be used with `navigator.geolocation.clearWatch` to stop watching for changes in position.
### Example
// onSuccess Callback
// This method accepts a `Position` object, which contains
// the current GPS coordinates
//
function onSuccess(position) {
var element = document.getElementById('geolocation');
element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' +
'Longitude: ' + position.coords.longitude + '<br />' +
'<hr />' + element.innerHTML;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Options: throw an error if no update is received every 30 seconds.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 30000 });
## geolocationOptions
Optional parameters to customize the retrieval of the geolocation
`Position`.
{ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };
### Options
- __enableHighAccuracy__: Provides a hint that the application needs the best possible results. By default, the device attempts to retrieve a `Position` using network-based methods. Setting this property to `true` tells the framework to use more accurate methods, such as satellite positioning. _(Boolean)_
- __timeout__: The maximum length of time (milliseconds) that is allowed to pass from the call to `navigator.geolocation.getCurrentPosition` or `geolocation.watchPosition` until the corresponding `geolocationSuccess` callback executes. If the `geolocationSuccess` callback is not invoked within this time, the `geolocationError` callback is passed a `PositionError.TIMEOUT` error code. (Note that when used in conjunction with `geolocation.watchPosition`, the `geolocationError` callback could be called on an interval every `timeout` milliseconds!) _(Number)_
- __maximumAge__: Accept a cached position whose age is no greater than the specified time in milliseconds. _(Number)_
### Android Quirks
Android 2.x emulators do not return a geolocation result unless the `enableHighAccuracy` option is set to `true`.
## navigator.geolocation.clearWatch
Stop watching for changes to the device's location referenced by the
`watchID` parameter.
navigator.geolocation.clearWatch(watchID);
### Parameters
- __watchID__: The id of the `watchPosition` interval to clear. (String)
### Example
// Options: watch for changes in position, and use the most
// accurate position acquisition method available.
//
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });
// ...later on...
navigator.geolocation.clearWatch(watchID);
## Position
Contains `Position` coordinates and timestamp, created by the geolocation API.
### Properties
- __coords__: A set of geographic coordinates. _(Coordinates)_
- __timestamp__: Creation timestamp for `coords`. _(Date)_
## Coordinates
A `Coordinates` object is attached to a `Position` object that is
available to callback functions in requests for the current position.
It contains a set of properties that describe the geographic coordinates of a position.
### Properties
* __latitude__: Latitude in decimal degrees. _(Number)_
* __longitude__: Longitude in decimal degrees. _(Number)_
* __altitude__: Height of the position in meters above the ellipsoid. _(Number)_
* __accuracy__: Accuracy level of the latitude and longitude coordinates in meters. _(Number)_
* __altitudeAccuracy__: Accuracy level of the altitude coordinate in meters. _(Number)_
* __heading__: Direction of travel, specified in degrees counting clockwise relative to the true north. _(Number)_
* __speed__: Current ground speed of the device, specified in meters per second. _(Number)_
### Amazon Fire OS Quirks
__altitudeAccuracy__: Not supported by Android devices, returning `null`.
### Android Quirks
__altitudeAccuracy__: Not supported by Android devices, returning `null`.
## PositionError
The `PositionError` object is passed to the `geolocationError`
callback function when an error occurs with navigator.geolocation.
### Properties
- __code__: One of the predefined error codes listed below.
- __message__: Error message describing the details of the error encountered.
### Constants
- `PositionError.PERMISSION_DENIED`
- Returned when users do not allow the app to retrieve position information. This is dependent on the platform.
- `PositionError.POSITION_UNAVAILABLE`
- Returned when the device is unable to retrieve a position. In general, this means the device is not connected to a network or can't get a satellite fix.
- `PositionError.TIMEOUT`
- Returned when the device is unable to retrieve a position within the time specified by the `timeout` included in `geolocationOptions`. When used with `navigator.geolocation.watchPosition`, this error could be repeatedly passed to the `geolocationError` callback every `timeout` milliseconds.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-globalization
This plugin obtains information and performs operations specific to the user's
locale, language, and timezone. Note the difference between locale and language:
locale controls how numbers, dates, and times are displayed for a region, while
language determines what language text appears as, independently of locale settings.
Often developers use locale to set both settings, but there is no reason a user
couldn't set her language to "English" but locale to "French", so that text is
displayed in English but dates, times, etc., are displayed as they are in France.
Unfortunately, most mobile platforms currently do not make a distinction between
these settings.
This plugin defines global `navigator.globalization` object.
Although in the global scope, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.globalization);
}
## Installation
cordova plugin add cordova-plugin-globalization
## Objects
- GlobalizationError
## Methods
- navigator.globalization.getPreferredLanguage
- navigator.globalization.getLocaleName
- navigator.globalization.dateToString
- navigator.globalization.stringToDate
- navigator.globalization.getDatePattern
- navigator.globalization.getDateNames
- navigator.globalization.isDayLightSavingsTime
- navigator.globalization.getFirstDayOfWeek
- navigator.globalization.numberToString
- navigator.globalization.stringToNumber
- navigator.globalization.getNumberPattern
- navigator.globalization.getCurrencyPattern
## navigator.globalization.getPreferredLanguage
Get the BCP 47 language tag for the client's current language.
navigator.globalization.getPreferredLanguage(successCallback, errorCallback);
### Description
Returns the BCP-47 compliant language identifier tag to the `successCallback`
with a `properties` object as a parameter. That object should have a `value`
property with a `String` value.
If there is an error getting the language, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.UNKNOWN_ERROR`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en-US` language, this should display a
popup dialog with the text `language: en-US`:
navigator.globalization.getPreferredLanguage(
function (language) {alert('language: ' + language.value + '\n');},
function () {alert('Error getting language\n');}
);
### Android Quirks
- Returns the ISO 639-1 two-letter language code, upper case ISO 3166-1
country code and variant separated by hyphens. Examples: "en", "en-US", "US"
### Windows Phone 8 Quirks
- Returns the ISO 639-1 two-letter language code and ISO 3166-1 country code
of the regional variant corresponding to the "Language" setting, separated by
a hyphen.
- Note that the regional variant is a property of the "Language" setting and
not determined by the unrelated "Country/Region" setting on Windows Phone.
### Windows Quirks
- Returns the ISO 639-1 two-letter language code and ISO 3166-1 country code
of the regional variant corresponding to the "Language" setting, separated by
a hyphen.
### Browser Quirks
- Falls back on getLocaleName
## navigator.globalization.getLocaleName
Returns the BCP 47 compliant tag for the client's current locale setting.
navigator.globalization.getLocaleName(successCallback, errorCallback);
### Description
Returns the BCP 47 compliant locale identifier string to the `successCallback`
with a `properties` object as a parameter. That object should have a `value`
property with a `String` value. The locale tag will consist of a two-letter lower
case language code, two-letter upper case country code, and (unspecified) variant
code, separated by a hyphen.
If there is an error getting the locale, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.UNKNOWN_ERROR`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en-US` locale, this displays a popup
dialog with the text `locale: en-US`.
navigator.globalization.getLocaleName(
function (locale) {alert('locale: ' + locale.value + '\n');},
function () {alert('Error getting locale\n');}
);
### Android Quirks
- Java does not distinguish between a set "langauge" and set "locale," so this
method is essentially the same as `navigator.globalizatin.getPreferredLanguage()`.
### Windows Phone 8 Quirks
- Returns the ISO 639-1 two-letter language code and ISO 3166-1 country code
of the regional variant corresponding to the "Regional Format" setting, separated
by a hyphen.
### Windows Quirks
- Locale setting can be changed in Control Panel -> Clock, Language and Region
-> Region -> Formats -> Format,
and in Settings -> Region -> Regional Format on Windows Phone 8.1.
### Browser Quirks
- IE returns the locale of operating system. Chrome and Firefox return browser language tag.
## navigator.globalization.dateToString
Returns a date formatted as a string according to the client's locale and timezone.
navigator.globalization.dateToString(date, successCallback, errorCallback, options);
### Description
Returns the formatted date `String` via a `value` property accessible
from the object passed as a parameter to the `successCallback`.
The inbound `date` parameter should be of type `Date`.
If there is an error formatting the date, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.FORMATTING_ERROR`.
The `options` parameter is optional, and its default values are:
{formatLength:'short', selector:'date and time'}
The `options.formatLength` can be `short`, `medium`, `long`, or `full`.
The `options.selector` can be `date`, `time` or `date and time`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
If the browser is set to the `en_US` locale, this displays a popup
dialog with text similar to `date: 9/25/2012 4:21PM` using the default
options:
navigator.globalization.dateToString(
new Date(),
function (date) { alert('date: ' + date.value + '\n'); },
function () { alert('Error getting dateString\n'); },
{ formatLength: 'short', selector: 'date and time' }
);
### Android Quirks
- `formatLength` options are a subset of Unicode
[UTS #35](http://unicode.org/reports/tr35/tr35-4.html). The default option
`short` depends on a user selected date format within
`Settings -> System -> Date & time -> Choose date format`,
which provide a `year` pattern only with 4 digits, not 2 digits.
This means that it is not completely aligned with
[ICU](http://demo.icu-project.org/icu-bin/locexp?d_=en_US&_=en_US).
### Windows Phone 8 Quirks
- The `formatLength` option supports only `short` and `full` values.
- The pattern for 'date and time' selector is always a full datetime format.
- The returned value may be not completely aligned with ICU depending on a user locale.
### Windows Quirks
- The `formatLength` option supports only `short` and `full` values.
- The pattern for 'date and time' selector is always a full datetime format.
- The returned value may be not completely aligned with ICU depending on a user locale.
### Browser Quirks
- Only 79 locales are supported because moment.js is used in this method.
- The returned value may be not completely aligned with ICU depending on a user locale.
- `time` selector supports `full` and `short` formatLength only.
### Firefox OS Quirks
- `formatLength` is not distinguishing `long` and `full`
- only one method of displaying date (no `long` or `full` version)
## navigator.globalization.getCurrencyPattern
Returns a pattern string to format and parse currency values according
to the client's user preferences and ISO 4217 currency code.
navigator.globalization.getCurrencyPattern(currencyCode, successCallback, errorCallback);
### Description
Returns the pattern to the `successCallback` with a `properties` object
as a parameter. That object should contain the following properties:
- __pattern__: The currency pattern to format and parse currency values. The patterns follow [Unicode Technical Standard #35](http://unicode.org/reports/tr35/tr35-4.html). _(String)_
- __code__: The ISO 4217 currency code for the pattern. _(String)_
- __fraction__: The number of fractional digits to use when parsing and formatting currency. _(Number)_
- __rounding__: The rounding increment to use when parsing and formatting. _(Number)_
- __decimal__: The decimal symbol to use for parsing and formatting. _(String)_
- __grouping__: The grouping symbol to use for parsing and formatting. _(String)_
The inbound `currencyCode` parameter should be a `String` of one of
the ISO 4217 currency codes, for example 'USD'.
If there is an error obtaining the pattern, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.FORMATTING_ERROR`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows 8
- Windows
### Example
When the browser is set to the `en_US` locale and the selected
currency is United States Dollars, this example displays a popup
dialog with text similar to the results that follow:
navigator.globalization.getCurrencyPattern(
'USD',
function (pattern) {
alert('pattern: ' + pattern.pattern + '\n' +
'code: ' + pattern.code + '\n' +
'fraction: ' + pattern.fraction + '\n' +
'rounding: ' + pattern.rounding + '\n' +
'decimal: ' + pattern.decimal + '\n' +
'grouping: ' + pattern.grouping);
},
function () { alert('Error getting pattern\n'); }
);
Expected result:
pattern: $#,##0.##;($#,##0.##)
code: USD
fraction: 2
rounding: 0
decimal: .
grouping: ,
### Windows Quirks
- Only 'code' and 'fraction' properties are supported
## navigator.globalization.getDateNames
Returns an array of the names of the months or days of the week,
depending on the client's user preferences and calendar.
navigator.globalization.getDateNames(successCallback, errorCallback, options);
### Description
Returns the array of names to the `successCallback` with a
`properties` object as a parameter. That object contains a `value`
property with an `Array` of `String` values. The array features names
starting from either the first month in the year or the first day of
the week, depending on the option selected.
If there is an error obtaining the names, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.UNKNOWN_ERROR`.
The `options` parameter is optional, and its default values are:
{type:'wide', item:'months'}
The value of `options.type` can be `narrow` or `wide`.
The value of `options.item` can be `months` or `days`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en_US` locale, this example displays
a series of twelve popup dialogs, one per month, with text similar to
`month: January`:
navigator.globalization.getDateNames(
function (names) {
for (var i = 0; i < names.value.length; i++) {
alert('month: ' + names.value[i] + '\n');
}
},
function () { alert('Error getting names\n'); },
{ type: 'wide', item: 'months' }
);
### Firefox OS Quirks
- `options.type` supports a `genitive` value, important for some languages
### Windows Phone 8 Quirks
- The array of months contains 13 elements.
- The returned array may be not completely aligned with ICU depending on a user locale.
### Windows Quirks
- The array of months contains 12 elements.
- The returned array may be not completely aligned with ICU depending on a user locale.
### Browser Quirks
- Date names are not completely aligned with ICU
- The array of months contains 12 elements.
## navigator.globalization.getDatePattern
Returns a pattern string to format and parse dates according to the
client's user preferences.
navigator.globalization.getDatePattern(successCallback, errorCallback, options);
### Description
Returns the pattern to the `successCallback`. The object passed in as
a parameter contains the following properties:
- __pattern__: The date and time pattern to format and parse dates. The patterns follow [Unicode Technical Standard #35](http://unicode.org/reports/tr35/tr35-4.html). _(String)_
- __timezone__: The abbreviated name of the time zone on the client. _(String)_
- __utc_offset__: The current difference in seconds between the client's time zone and coordinated universal time. _(Number)_
- __dst_offset__: The current daylight saving time offset in seconds between the client's non-daylight saving's time zone and the client's daylight saving's time zone. _(Number)_
If there is an error obtaining the pattern, the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.PATTERN_ERROR`.
The `options` parameter is optional, and defaults to the following values:
{formatLength:'short', selector:'date and time'}
The `options.formatLength` can be `short`, `medium`, `long`, or
`full`. The `options.selector` can be `date`, `time` or `date and
time`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en_US` locale, this example displays
a popup dialog with text such as `pattern: M/d/yyyy h:mm a`:
function checkDatePattern() {
navigator.globalization.getDatePattern(
function (date) { alert('pattern: ' + date.pattern + '\n'); },
function () { alert('Error getting pattern\n'); },
{ formatLength: 'short', selector: 'date and time' }
);
}
### Windows Phone 8 Quirks
- The `formatLength` supports only `short` and `full` values.
- The `pattern` for `date and time` pattern returns only full datetime format.
- The `timezone` returns the full time zone name.
- The `dst_offset` property is not supported, and always returns zero.
- The pattern may be not completely aligned with ICU depending on a user locale.
### Windows Quirks
- The `formatLength` supports only `short` and `full` values.
- The `pattern` for `date and time` pattern returns only full datetime format.
- The `timezone` returns the full time zone name.
- The `dst_offset` property is not supported, and always returns zero.
- The pattern may be not completely aligned with ICU depending on a user locale.
### Browser Quirks
- The 'pattern' property is not supported and returns empty string.
- Only Chrome returns 'timezone' property. Its format is "Part of the world/{City}".
Other browsers return empty string.
## navigator.globalization.getFirstDayOfWeek
Returns the first day of the week according to the client's user
preferences and calendar.
navigator.globalization.getFirstDayOfWeek(successCallback, errorCallback);
### Description
The days of the week are numbered starting from 1, where 1 is assumed
to be Sunday. Returns the day to the `successCallback` with a
`properties` object as a parameter. That object should have a `value`
property with a `Number` value.
If there is an error obtaining the pattern, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.UNKNOWN_ERROR`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en_US` locale, this displays a
popup dialog with text similar to `day: 1`.
navigator.globalization.getFirstDayOfWeek(
function (day) {alert('day: ' + day.value + '\n');},
function () {alert('Error getting day\n');}
);
### Windows Quirks
- On Windows 8.0/8.1 the value depends on user' calendar preferences. On Windows Phone 8.1
the value depends on current locale.
### Browser Quirks
- Only 79 locales are supported because moment.js is used in this method.
## navigator.globalization.getNumberPattern
Returns a pattern string to format and parse numbers according to the client's user preferences.
navigator.globalization.getNumberPattern(successCallback, errorCallback, options);
### Description
Returns the pattern to the `successCallback` with a `properties` object
as a parameter. That object contains the following properties:
- __pattern__: The number pattern to format and parse numbers. The patterns follow [Unicode Technical Standard #35](http://unicode.org/reports/tr35/tr35-4.html). _(String)_
- __symbol__: The symbol to use when formatting and parsing, such as a percent or currency symbol. _(String)_
- __fraction__: The number of fractional digits to use when parsing and formatting numbers. _(Number)_
- __rounding__: The rounding increment to use when parsing and formatting. _(Number)_
- __positive__: The symbol to use for positive numbers when parsing and formatting. _(String)_
- __negative__: The symbol to use for negative numbers when parsing and formatting. _(String)_
- __decimal__: The decimal symbol to use for parsing and formatting. _(String)_
- __grouping__: The grouping symbol to use for parsing and formatting. _(String)_
If there is an error obtaining the pattern, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.PATTERN_ERROR`.
The `options` parameter is optional, and default values are:
{type:'decimal'}
The `options.type` can be `decimal`, `percent`, or `currency`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en_US` locale, this should display a
popup dialog with text similar to the results that follow:
navigator.globalization.getNumberPattern(
function (pattern) {alert('pattern: ' + pattern.pattern + '\n' +
'symbol: ' + pattern.symbol + '\n' +
'fraction: ' + pattern.fraction + '\n' +
'rounding: ' + pattern.rounding + '\n' +
'positive: ' + pattern.positive + '\n' +
'negative: ' + pattern.negative + '\n' +
'decimal: ' + pattern.decimal + '\n' +
'grouping: ' + pattern.grouping);},
function () {alert('Error getting pattern\n');},
{type:'decimal'}
);
Results:
pattern: #,##0.###
symbol: .
fraction: 0
rounding: 0
positive:
negative: -
decimal: .
grouping: ,
### Windows Phone 8 Quirks
- The `pattern` property is not supported, and returns an empty string.
- The `fraction` property is not supported, and returns zero.
### Windows Quirks
- The `pattern` property is not supported, and returns an empty string.
### Browser Quirks
- getNumberPattern is supported in Chrome only; the only defined property is `pattern`.
## navigator.globalization.isDayLightSavingsTime
Indicates whether daylight savings time is in effect for a given date
using the client's time zone and calendar.
navigator.globalization.isDayLightSavingsTime(date, successCallback, errorCallback);
### Description
Indicates whether or not daylight savings time is in effect to the
`successCallback` with a `properties` object as a parameter. That object
should have a `dst` property with a `Boolean` value. A `true` value
indicates that daylight savings time is in effect for the given date,
and `false` indicates that it is not.
The inbound parameter `date` should be of type `Date`.
If there is an error reading the date, then the `errorCallback`
executes. The error's expected code is `GlobalizationError.UNKNOWN_ERROR`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
During the summer, and if the browser is set to a DST-enabled
timezone, this should display a popup dialog with text similar to
`dst: true`:
navigator.globalization.isDayLightSavingsTime(
new Date(),
function (date) {alert('dst: ' + date.dst + '\n');},
function () {alert('Error getting names\n');}
);
## navigator.globalization.numberToString
Returns a number formatted as a string according to the client's user preferences.
navigator.globalization.numberToString(number, successCallback, errorCallback, options);
### Description
Returns the formatted number string to the `successCallback` with a
`properties` object as a parameter. That object should have a `value`
property with a `String` value.
If there is an error formatting the number, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.FORMATTING_ERROR`.
The `options` parameter is optional, and its default values are:
{type:'decimal'}
The `options.type` can be 'decimal', 'percent', or 'currency'.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en_US` locale, this displays a popup
dialog with text similar to `number: 3.142`:
navigator.globalization.numberToString(
3.1415926,
function (number) {alert('number: ' + number.value + '\n');},
function () {alert('Error getting number\n');},
{type:'decimal'}
);
### Windows Quirks
- Windows 8.0 does not support number rounding, therefore values will not be rounded automatically.
- On Windows 8.1 and Windows Phone 8.1 fractional part is being truncated instead of rounded in case of `percent` number type therefore fractional digits count is set to 0.
- `percent` numbers are not grouped as they can't be parsed in stringToNumber if grouped.
### Browser Quirks
- `currency` type is not supported.
## navigator.globalization.stringToDate
Parses a date formatted as a string, according to the client's user
preferences and calendar using the time zone of the client, and
returns the corresponding date object.
navigator.globalization.stringToDate(dateString, successCallback, errorCallback, options);
### Description
Returns the date to the success callback with a `properties` object as
a parameter. That object should have the following properties:
- __year__: The four digit year. _(Number)_
- __month__: The month from (0-11). _(Number)_
- __day__: The day from (1-31). _(Number)_
- __hour__: The hour from (0-23). _(Number)_
- __minute__: The minute from (0-59). _(Number)_
- __second__: The second from (0-59). _(Number)_
- __millisecond__: The milliseconds (from 0-999), not available on all platforms. _(Number)_
The inbound `dateString` parameter should be of type `String`.
The `options` parameter is optional, and defaults to the following
values:
{formatLength:'short', selector:'date and time'}
The `options.formatLength` can be `short`, `medium`, `long`, or
`full`. The `options.selector` can be `date`, `time` or `date and
time`.
If there is an error parsing the date string, then the `errorCallback`
executes with a `GlobalizationError` object as a parameter. The
error's expected code is `GlobalizationError.PARSING_ERROR`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
### Example
When the browser is set to the `en_US` locale, this displays a
popup dialog with text similar to `month:8 day:25 year:2012`. Note
that the month integer is one less than the string, as the month
integer represents an array index.
navigator.globalization.stringToDate(
'9/25/2012',
function (date) {alert('month:' + date.month +
' day:' + date.day +
' year:' + date.year + '\n');},
function () {alert('Error getting date\n');},
{selector: 'date'}
);
### Windows Phone 8 Quirks
- The `formatLength` option supports only `short` and `full` values.
- The pattern for 'date and time' selector is always a full datetime format.
- The inbound `dateString` parameter should be formed in compliance with a pattern returned by getDatePattern.
This pattern may be not completely aligned with ICU depending on a user locale.
### Windows Quirks
- The `formatLength` option supports only `short` and `full` values.
- The pattern for 'date and time' selector is always a full datetime format.
- The inbound `dateString` parameter should be formed in compliance with a pattern returned by getDatePattern.
This pattern may be not completely aligned with ICU depending on a user locale.
### Browser Quirks
- Only 79 locales are supported because moment.js is used in this method.
- Inbound string should be aligned with `dateToString` output format and may not completely aligned with ICU depending on a user locale.
- `time` selector supports `full` and `short` formatLength only.
## navigator.globalization.stringToNumber
Parses a number formatted as a string according to the client's user
preferences and returns the corresponding number.
navigator.globalization.stringToNumber(string, successCallback, errorCallback, options);
### Description
Returns the number to the `successCallback` with a `properties` object
as a parameter. That object should have a `value` property with a
`Number` value.
If there is an error parsing the number string, then the
`errorCallback` executes with a `GlobalizationError` object as a
parameter. The error's expected code is
`GlobalizationError.PARSING_ERROR`.
The `options` parameter is optional, and defaults to the following
values:
{type:'decimal'}
The `options.type` can be `decimal`, `percent`, or `currency`.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
### Example
When the browser is set to the `en_US` locale, this should display a
popup dialog with text similar to `number: 1234.56`:
navigator.globalization.stringToNumber(
'1234.56',
function (number) {alert('number: ' + number.value + '\n');},
function () {alert('Error getting number\n');},
{type:'decimal'}
);
### Windows Phone 8 Quirks
- In case of `percent` type the returned value is not divided by 100.
### Windows Quirks
- The string must strictly conform to the locale format. For example, percent symbol should be
separated by space for 'en-US' locale if the type parameter is 'percent'.
- `percent` numbers must not be grouped to be parsed correctly.
## GlobalizationError
An object representing a error from the Globalization API.
### Properties
- __code__: One of the following codes representing the error type _(Number)_
- GlobalizationError.UNKNOWN_ERROR: 0
- GlobalizationError.FORMATTING_ERROR: 1
- GlobalizationError.PARSING_ERROR: 2
- GlobalizationError.PATTERN_ERROR: 3
- __message__: A text message that includes the error's explanation and/or details _(String)_
### Description
This object is created and populated by Cordova, and returned to a callback in the case of an error.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
### Example
When the following error callback executes, it displays a
popup dialog with the text similar to `code: 3` and `message:`
function errorCallback(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
};
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-inappbrowser
This plugin provides a web browser view that displays when calling `cordova.InAppBrowser.open()`.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
The `cordova.InAppBrowser.open()` function is defined to be a drop-in replacement
for the `window.open()` function. Existing `window.open()` calls can use the
InAppBrowser window, by replacing window.open:
window.open = cordova.InAppBrowser.open;
The InAppBrowser window behaves like a standard web browser,
and can't access Cordova APIs. For this reason, the InAppBrowser is recommended
if you need to load third-party (untrusted) content, instead of loading that
into the main Cordova webview. The InAppBrowser is not subject to the
whitelist, nor is opening links in the system browser.
The InAppBrowser provides by default its own GUI controls for the user (back,
forward, done).
For backwards compatibility, this plugin also hooks `window.open`.
However, the plugin-installed hook of `window.open` can have unintended side
effects (especially if this plugin is included only as a dependency of another
plugin). The hook of `window.open` will be removed in a future major release.
Until the hook is removed from the plugin, apps can manually restore the default
behaviour:
delete window.open // Reverts the call back to it's prototype's default
Although `window.open` is in the global scope, InAppBrowser is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("window.open works well");
}
## Installation
cordova plugin add cordova-plugin-inappbrowser
If you want all page loads in your app to go through the InAppBrowser, you can
simply hook `window.open` during initialization. For example:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.open = cordova.InAppBrowser.open;
}
## cordova.InAppBrowser.open
Opens a URL in a new `InAppBrowser` instance, the current browser
instance, or the system browser.
var ref = cordova.InAppBrowser.open(url, target, options);
- __ref__: Reference to the `InAppBrowser` window. _(InAppBrowser)_
- __url__: The URL to load _(String)_. Call `encodeURI()` on this if the URL contains Unicode characters.
- __target__: The target in which to load the URL, an optional parameter that defaults to `_self`. _(String)_
- `_self`: Opens in the Cordova WebView if the URL is in the white list, otherwise it opens in the `InAppBrowser`.
- `_blank`: Opens in the `InAppBrowser`.
- `_system`: Opens in the system's web browser.
- __options__: Options for the `InAppBrowser`. Optional, defaulting to: `location=yes`. _(String)_
The `options` string must not contain any blank space, and each feature's name/value pairs must be separated by a comma. Feature names are case insensitive. All platforms support the value below:
- __location__: Set to `yes` or `no` to turn the `InAppBrowser`'s location bar on or off.
Android only:
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The loadstop event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
- __clearcache__: set to `yes` to have the browser's cookie cache cleared before the new window is opened
- __clearsessioncache__: set to `yes` to have the session cookie cache cleared before the new window is opened
- __zoom__: set to `yes` to show Android browser's zoom controls, set to `no` to hide them. Default value is `yes`.
- __hardwareback__: set to `yes` to use the hardware back button to navigate backwards through the `InAppBrowser`'s history. If there is no previous page, the `InAppBrowser` will close. The default value is `yes`, so you must set it to `no` if you want the back button to simply close the InAppBrowser.
iOS only:
- __closebuttoncaption__: set to a string to use as the __Done__ button's caption. Note that you need to localize this value yourself.
- __disallowoverscroll__: Set to `yes` or `no` (default is `no`). Turns on/off the UIWebViewBounce property.
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The loadstop event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
- __clearcache__: set to `yes` to have the browser's cookie cache cleared before the new window is opened
- __clearsessioncache__: set to `yes` to have the session cookie cache cleared before the new window is opened
- __toolbar__: set to `yes` or `no` to turn the toolbar on or off for the InAppBrowser (defaults to `yes`)
- __enableViewportScale__: Set to `yes` or `no` to prevent viewport scaling through a meta tag (defaults to `no`).
- __mediaPlaybackRequiresUserAction__: Set to `yes` or `no` to prevent HTML5 audio or video from autoplaying (defaults to `no`).
- __allowInlineMediaPlayback__: Set to `yes` or `no` to allow in-line HTML5 media playback, displaying within the browser window rather than a device-specific playback interface. The HTML's `video` element must also include the `webkit-playsinline` attribute (defaults to `no`)
- __keyboardDisplayRequiresUserAction__: Set to `yes` or `no` to open the keyboard when form elements receive focus via JavaScript's `focus()` call (defaults to `yes`).
- __suppressesIncrementalRendering__: Set to `yes` or `no` to wait until all new view content is received before being rendered (defaults to `no`).
- __presentationstyle__: Set to `pagesheet`, `formsheet` or `fullscreen` to set the [presentation style](http://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalPresentationStyle) (defaults to `fullscreen`).
- __transitionstyle__: Set to `fliphorizontal`, `crossdissolve` or `coververtical` to set the [transition style](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html#//apple_ref/occ/instp/UIViewController/modalTransitionStyle) (defaults to `coververtical`).
- __toolbarposition__: Set to `top` or `bottom` (default is `bottom`). Causes the toolbar to be at the top or bottom of the window.
Windows only:
- __hidden__: set to `yes` to create the browser and load the page, but not show it. The loadstop event fires when loading is complete. Omit or set to `no` (default) to have the browser open and load normally.
- __fullscreen__: set to `yes` to create the browser control without a border around it. Please note that if __location=no__ is also specified, there will be no control presented to user to close IAB window.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
### Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var ref2 = cordova.InAppBrowser.open(encodeURI('http://ja.m.wikipedia.org/wiki/ハングル'), '_blank', 'location=yes');
### Firefox OS Quirks
As plugin doesn't enforce any design there is a need to add some CSS rules if
opened with `target='_blank'`. The rules might look like these
``` css
.inAppBrowserWrap {
background-color: rgba(0,0,0,0.75);
color: rgba(235,235,235,1.0);
}
.inAppBrowserWrap menu {
overflow: auto;
list-style-type: none;
padding-left: 0;
}
.inAppBrowserWrap menu li {
font-size: 25px;
height: 25px;
float: left;
margin: 0 10px;
padding: 3px 10px;
text-decoration: none;
color: #ccc;
display: block;
background: rgba(30,30,30,0.50);
}
.inAppBrowserWrap menu li.disabled {
color: #777;
}
```
### Windows Quirks
Similar to Firefox OS IAB window visual behaviour can be overridden via `inAppBrowserWrap`/`inAppBrowserWrapFullscreen` CSS classes
### Browser Quirks
- Plugin is implemented via iframe,
- Navigation history (`back` and `forward` buttons in LocationBar) is not implemented.
## InAppBrowser
The object returned from a call to `cordova.InAppBrowser.open`.
### Methods
- addEventListener
- removeEventListener
- close
- show
- executeScript
- insertCSS
## addEventListener
> Adds a listener for an event from the `InAppBrowser`.
ref.addEventListener(eventname, callback);
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
- __eventname__: the event to listen for _(String)_
- __loadstart__: event fires when the `InAppBrowser` starts to load a URL.
- __loadstop__: event fires when the `InAppBrowser` finishes loading a URL.
- __loaderror__: event fires when the `InAppBrowser` encounters an error when loading a URL.
- __exit__: event fires when the `InAppBrowser` window is closed.
- __callback__: the function that executes when the event fires. The function is passed an `InAppBrowserEvent` object as a parameter.
### InAppBrowserEvent Properties
- __type__: the eventname, either `loadstart`, `loadstop`, `loaderror`, or `exit`. _(String)_
- __url__: the URL that was loaded. _(String)_
- __code__: the error code, only in the case of `loaderror`. _(Number)_
- __message__: the error message, only in the case of `loaderror`. _(String)_
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
### Browser Quirks
`loadstart` and `loaderror` events are not being fired.
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
## removeEventListener
> Removes a listener for an event from the `InAppBrowser`.
ref.removeEventListener(eventname, callback);
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
- __eventname__: the event to stop listening for. _(String)_
- __loadstart__: event fires when the `InAppBrowser` starts to load a URL.
- __loadstop__: event fires when the `InAppBrowser` finishes loading a URL.
- __loaderror__: event fires when the `InAppBrowser` encounters an error loading a URL.
- __exit__: event fires when the `InAppBrowser` window is closed.
- __callback__: the function to execute when the event fires.
The function is passed an `InAppBrowserEvent` object.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', myCallback);
ref.removeEventListener('loadstart', myCallback);
## close
> Closes the `InAppBrowser` window.
ref.close();
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
### Supported Platforms
- Amazon Fire OS
- Android
- Firefox OS
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
## show
> Displays an InAppBrowser window that was opened hidden. Calling this has no effect if the InAppBrowser was already visible.
ref.show();
- __ref__: reference to the InAppBrowser window (`InAppBrowser`)
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
## executeScript
> Injects JavaScript code into the `InAppBrowser` window
ref.executeScript(details, callback);
- __ref__: reference to the `InAppBrowser` window. _(InAppBrowser)_
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
- __file__: URL of the script to inject.
- __code__: Text of the script to inject.
- __callback__: the function that executes after the JavaScript code is injected.
- If the injected script is of type `code`, the callback executes
with a single parameter, which is the return value of the
script, wrapped in an `Array`. For multi-line scripts, this is
the return value of the last statement, or the last expression
evaluated.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
### Browser Quirks
- only __code__ key is supported.
### Windows Quirks
Due to [MSDN docs](https://msdn.microsoft.com/en-us/library/windows.ui.xaml.controls.webview.invokescriptasync.aspx) the invoked script can return only string values, otherwise the parameter, passed to __callback__ will be `[null]`.
## insertCSS
> Injects CSS into the `InAppBrowser` window.
ref.insertCSS(details, callback);
- __ref__: reference to the `InAppBrowser` window _(InAppBrowser)_
- __injectDetails__: details of the script to run, specifying either a `file` or `code` key. _(Object)_
- __file__: URL of the stylesheet to inject.
- __code__: Text of the stylesheet to inject.
- __callback__: the function that executes after the CSS is injected.
### Supported Platforms
- Amazon Fire OS
- Android
- iOS
- Windows
### Quick Example
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-legacy-whitelist
This plugin implements the Cordova 3.6 Whitelist policy for Cordova 4.0.
Please use cordova-plugin-whitelist instead, as it's more secure.
Supported on:
- cordova-android@4.0.0
- cordova-ios@4.0.0
## Usage:
Use `<access>` tags, just as in previous versions of Cordova.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-media
This plugin provides the ability to record and play back audio files on a device.
__NOTE__: The current implementation does not adhere to a W3C
specification for media capture, and is provided for convenience only.
A future implementation will adhere to the latest W3C specification
and may deprecate the current APIs.
This plugin defines a global `Media` Constructor.
Although in the global scope, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(Media);
}
## Installation
cordova plugin add cordova-plugin-media
## Supported Platforms
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Tizen
- Windows 8
- Windows
- Browser
## Windows Phone Quirks
- Only one media file can be played back at a time.
- There are strict restrictions on how your application interacts with other media. See the [Microsoft documentation for details][url].
[url]: http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184838(v=vs.92).aspx
## Media
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
### Parameters
- __src__: A URI containing the audio content. _(DOMString)_
- __mediaSuccess__: (Optional) The callback that executes after a `Media` object has completed the current play, record, or stop action. _(Function)_
- __mediaError__: (Optional) The callback that executes if an error occurs. _(Function)_
- __mediaStatus__: (Optional) The callback that executes to indicate status changes. _(Function)_
__NOTE__: `cdvfile` path is supported as `src` parameter:
```javascript
var my_media = new Media('cdvfile://localhost/temporary/recording.mp3', ...);
```
### Constants
The following constants are reported as the only parameter to the
`mediaStatus` callback:
- `Media.MEDIA_NONE` = 0;
- `Media.MEDIA_STARTING` = 1;
- `Media.MEDIA_RUNNING` = 2;
- `Media.MEDIA_PAUSED` = 3;
- `Media.MEDIA_STOPPED` = 4;
### Methods
- `media.getCurrentPosition`: Returns the current position within an audio file.
- `media.getDuration`: Returns the duration of an audio file.
- `media.play`: Start or resume playing an audio file.
- `media.pause`: Pause playback of an audio file.
- `media.release`: Releases the underlying operating system's audio resources.
- `media.seekTo`: Moves the position within the audio file.
- `media.setVolume`: Set the volume for audio playback.
- `media.startRecord`: Start recording an audio file.
- `media.stopRecord`: Stop recording an audio file.
- `media.stop`: Stop playing an audio file.
### Additional ReadOnly Parameters
- __position__: The position within the audio playback, in seconds.
- Not automatically updated during play; call `getCurrentPosition` to update.
- __duration__: The duration of the media, in seconds.
## media.getCurrentPosition
Returns the current position within an audio file. Also updates the `Media` object's `position` parameter.
media.getCurrentPosition(mediaSuccess, [mediaError]);
### Parameters
- __mediaSuccess__: The callback that is passed the current position in seconds.
- __mediaError__: (Optional) The callback to execute if an error occurs.
### Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
// Update media position every second
var mediaTimer = setInterval(function () {
// get media position
my_media.getCurrentPosition(
// success callback
function (position) {
if (position > -1) {
console.log((position) + " sec");
}
},
// error callback
function (e) {
console.log("Error getting pos=" + e);
}
);
}, 1000);
## media.getDuration
Returns the duration of an audio file in seconds. If the duration is unknown, it returns a value of -1.
media.getDuration();
### Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
// Get duration
var counter = 0;
var timerDur = setInterval(function() {
counter = counter + 100;
if (counter > 2000) {
clearInterval(timerDur);
}
var dur = my_media.getDuration();
if (dur > 0) {
clearInterval(timerDur);
document.getElementById('audio_duration').innerHTML = (dur) + " sec";
}
}, 100);
## media.pause
Pauses playing an audio file.
media.pause();
### Quick Example
// Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function () { console.log("playAudio():Audio Success"); },
// error callback
function (err) { console.log("playAudio():Audio Error: " + err); }
);
// Play audio
my_media.play();
// Pause after 10 seconds
setTimeout(function () {
media.pause();
}, 10000);
}
## media.play
Starts or resumes playing an audio file.
media.play();
### Quick Example
// Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function () {
console.log("playAudio():Audio Success");
},
// error callback
function (err) {
console.log("playAudio():Audio Error: " + err);
}
);
// Play audio
my_media.play();
}
### iOS Quirks
- __numberOfLoops__: Pass this option to the `play` method to specify
the number of times you want the media file to play, e.g.:
var myMedia = new Media("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3")
myMedia.play({ numberOfLoops: 2 })
- __playAudioWhenScreenIsLocked__: Pass in this option to the `play`
method to specify whether you want to allow playback when the screen
is locked. If set to `true` (the default value), the state of the
hardware mute button is ignored, e.g.:
var myMedia = new Media("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3")
myMedia.play({ playAudioWhenScreenIsLocked : false })
- __order of file search__: When only a file name or simple path is
provided, iOS searches in the `www` directory for the file, then in
the application's `documents/tmp` directory:
var myMedia = new Media("audio/beer.mp3")
myMedia.play() // first looks for file in www/audio/beer.mp3 then in <application>/documents/tmp/audio/beer.mp3
## media.release
Releases the underlying operating system's audio resources.
This is particularly important for Android, since there are a finite amount of
OpenCore instances for media playback. Applications should call the `release`
function for any `Media` resource that is no longer needed.
media.release();
### Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
my_media.play();
my_media.stop();
my_media.release();
## media.seekTo
Sets the current position within an audio file.
media.seekTo(milliseconds);
### Parameters
- __milliseconds__: The position to set the playback position within the audio, in milliseconds.
### Quick Example
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
my_media.play();
// SeekTo to 10 seconds after 5 seconds
setTimeout(function() {
my_media.seekTo(10000);
}, 5000);
### BlackBerry 10 Quirks
- Not supported on BlackBerry OS 5 devices.
## media.setVolume
Set the volume for an audio file.
media.setVolume(volume);
### Parameters
- __volume__: The volume to set for playback. The value must be within the range of 0.0 to 1.0.
### Supported Platforms
- Android
- iOS
### Quick Example
// Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: "+err);
});
// Play audio
my_media.play();
// Mute volume after 2 seconds
setTimeout(function() {
my_media.setVolume('0.0');
}, 2000);
// Set volume to 1.0 after 5 seconds
setTimeout(function() {
my_media.setVolume('1.0');
}, 5000);
}
## media.startRecord
Starts recording an audio file.
media.startRecord();
### Supported Platforms
- Android
- iOS
- Windows Phone 7 and 8
- Windows
### Quick Example
// Record audio
//
function recordAudio() {
var src = "myrecording.mp3";
var mediaRec = new Media(src,
// success callback
function() {
console.log("recordAudio():Audio Success");
},
// error callback
function(err) {
console.log("recordAudio():Audio Error: "+ err.code);
});
// Record audio
mediaRec.startRecord();
}
### Android Quirks
- Android devices record audio in Adaptive Multi-Rate format. The specified file should end with a _.amr_ extension.
- The hardware volume controls are wired up to the media volume while any Media objects are alive. Once the last created Media object has `release()` called on it, the volume controls revert to their default behaviour. The controls are also reset on page navigation, as this releases all Media objects.
### iOS Quirks
- iOS only records to files of type _.wav_ and returns an error if the file name extension is not correct.
- If a full path is not provided, the recording is placed in the application's `documents/tmp` directory. This can be accessed via the `File` API using `LocalFileSystem.TEMPORARY`. Any subdirectory specified at record time must already exist.
- Files can be recorded and played back using the documents URI:
var myMedia = new Media("documents://beer.mp3")
### Windows Quirks
- Windows devices can use MP3, M4A and WMA formats for recorded audio. However in most cases it is not possible to use MP3 for audio recording on _Windows Phone 8.1_ devices, because an MP3 encoder is [not shipped with Windows Phone](https://msdn.microsoft.com/en-us/library/windows/apps/windows.media.mediaproperties.mediaencodingprofile.createmp3.aspx).
- If a full path is not provided, the recording is placed in the AppData/temp directory. This can be accessed via the `File` API using `LocalFileSystem.TEMPORARY` or 'ms-appdata:///temp/<filename>' URI.
- Any subdirectory specified at record time must already exist.
### Tizen Quirks
- Not supported on Tizen devices.
## media.stop
Stops playing an audio file.
media.stop();
### Quick Example
// Play audio
//
function playAudio(url) {
// Play the audio file at url
var my_media = new Media(url,
// success callback
function() {
console.log("playAudio():Audio Success");
},
// error callback
function(err) {
console.log("playAudio():Audio Error: "+err);
}
);
// Play audio
my_media.play();
// Pause after 10 seconds
setTimeout(function() {
my_media.stop();
}, 10000);
}
## media.stopRecord
Stops recording an audio file.
media.stopRecord();
### Supported Platforms
- Android
- iOS
- Windows Phone 7 and 8
- Windows
### Quick Example
// Record audio
//
function recordAudio() {
var src = "myrecording.mp3";
var mediaRec = new Media(src,
// success callback
function() {
console.log("recordAudio():Audio Success");
},
// error callback
function(err) {
console.log("recordAudio():Audio Error: "+ err.code);
}
);
// Record audio
mediaRec.startRecord();
// Stop recording after 10 seconds
setTimeout(function() {
mediaRec.stopRecord();
}, 10000);
}
### Tizen Quirks
- Not supported on Tizen devices.
## MediaError
A `MediaError` object is returned to the `mediaError` callback
function when an error occurs.
### Properties
- __code__: One of the predefined error codes listed below.
- __message__: An error message describing the details of the error.
### Constants
- `MediaError.MEDIA_ERR_ABORTED` = 1
- `MediaError.MEDIA_ERR_NETWORK` = 2
- `MediaError.MEDIA_ERR_DECODE` = 3
- `MediaError.MEDIA_ERR_NONE_SUPPORTED` = 4
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-media-capture
This plugin provides access to the device's audio, image, and video capture capabilities.
__WARNING__: Collection and use of images, video, or
audio from the device's camera or microphone raises important privacy
issues. Your app's privacy policy should discuss how the app uses
such sensors and whether the data recorded is shared with any other
parties. In addition, if the app's use of the camera or microphone is
not apparent in the user interface, you should provide a just-in-time
notice before the app accesses the camera or microphone (if the
device operating system doesn't do so already). That notice should
provide the same information noted above, as well as obtaining the
user's permission (e.g., by presenting choices for __OK__ and __No
Thanks__). Note that some app marketplaces may require your app to
provide just-in-time notice and obtain permission from the user prior
to accessing the camera or microphone. For more information, please
see the Privacy Guide.
This plugin defines global `navigator.device.capture` object.
Although in the global scope, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.device.capture);
}
## Installation
cordova plugin add cordova-plugin-media-capture
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
## Objects
- Capture
- CaptureAudioOptions
- CaptureImageOptions
- CaptureVideoOptions
- CaptureCallback
- CaptureErrorCB
- ConfigurationData
- MediaFile
- MediaFileData
## Methods
- capture.captureAudio
- capture.captureImage
- capture.captureVideo
- MediaFile.getFormatData
## Properties
- __supportedAudioModes__: The audio recording formats supported by the device. (ConfigurationData[])
- __supportedImageModes__: The recording image sizes and formats supported by the device. (ConfigurationData[])
- __supportedVideoModes__: The recording video resolutions and formats supported by the device. (ConfigurationData[])
## capture.captureAudio
> Start the audio recorder application and return information about captured audio clip files.
navigator.device.capture.captureAudio(
CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureAudioOptions options]
);
### Description
Starts an asynchronous operation to capture audio recordings using the
device's default audio recording application. The operation allows
the device user to capture multiple recordings in a single session.
The capture operation ends when either the user exits the audio
recording application, or the maximum number of recordings specified
by `CaptureAudioOptions.limit` is reached. If no `limit` parameter
value is specified, it defaults to one (1), and the capture operation
terminates after the user records a single audio clip.
When the capture operation finishes, the `CaptureCallback` executes
with an array of `MediaFile` objects describing each captured audio
clip file. If the user terminates the operation before an audio clip
is captured, the `CaptureErrorCallback` executes with a `CaptureError`
object, featuring the `CaptureError.CAPTURE_NO_MEDIA_FILES` error
code.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
### Example
// capture callback
var captureSuccess = function(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
// do something interesting with the file
}
};
// capture error callback
var captureError = function(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
// start audio capture
navigator.device.capture.captureAudio(captureSuccess, captureError, {limit:2});
### iOS Quirks
- iOS does not have a default audio recording application, so a simple user interface is provided.
### Windows Phone 7 and 8 Quirks
- Windows Phone 7 does not have a default audio recording application, so a simple user interface is provided.
## CaptureAudioOptions
> Encapsulates audio capture configuration options.
### Properties
- __limit__: The maximum number of audio clips the device user can record in a single capture operation. The value must be greater than or equal to 1 (defaults to 1).
- __duration__: The maximum duration of an audio sound clip, in seconds.
### Example
// limit capture operation to 3 media files, no longer than 10 seconds each
var options = { limit: 3, duration: 10 };
navigator.device.capture.captureAudio(captureSuccess, captureError, options);
### Amazon Fire OS Quirks
- The `duration` parameter is not supported. Recording lengths cannot be limited programmatically.
### Android Quirks
- The `duration` parameter is not supported. Recording lengths can't be limited programmatically.
### BlackBerry 10 Quirks
- The `duration` parameter is not supported. Recording lengths can't be limited programmatically.
- The `limit` parameter is not supported, so only one recording can be created for each invocation.
### iOS Quirks
- The `limit` parameter is not supported, so only one recording can be created for each invocation.
## capture.captureImage
> Start the camera application and return information about captured image files.
navigator.device.capture.captureImage(
CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureImageOptions options]
);
### Description
Starts an asynchronous operation to capture images using the device's
camera application. The operation allows users to capture more than
one image in a single session.
The capture operation ends either when the user closes the camera
application, or the maximum number of recordings specified by
`CaptureAudioOptions.limit` is reached. If no `limit` value is
specified, it defaults to one (1), and the capture operation
terminates after the user captures a single image.
When the capture operation finishes, it invokes the `CaptureCB`
callback with an array of `MediaFile` objects describing each captured
image file. If the user terminates the operation before capturing an
image, the `CaptureErrorCB` callback executes with a `CaptureError`
object featuring a `CaptureError.CAPTURE_NO_MEDIA_FILES` error code.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
### Windows Phone 7 Quirks
Invoking the native camera application while your device is connected
via Zune does not work, and the error callback executes.
### Browser Quirks
Works in Chrome, Firefox and Opera only (since IE and Safari doesn't supports
navigator.getUserMedia API)
Displaying images using captured file's URL available in Chrome/Opera only.
Firefox stores captured images in IndexedDB storage (see File plugin documentation),
and due to this the only way to show captured image is to read it and show using its DataURL.
### Example
// capture callback
var captureSuccess = function(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
// do something interesting with the file
}
};
// capture error callback
var captureError = function(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
// start image capture
navigator.device.capture.captureImage(captureSuccess, captureError, {limit:2});
## CaptureImageOptions
> Encapsulates image capture configuration options.
### Properties
- __limit__: The maximum number of images the user can capture in a single capture operation. The value must be greater than or equal to 1 (defaults to 1).
### Example
// limit capture operation to 3 images
var options = { limit: 3 };
navigator.device.capture.captureImage(captureSuccess, captureError, options);
### iOS Quirks
- The __limit__ parameter is not supported, and only one image is taken per invocation.
## capture.captureVideo
> Start the video recorder application and return information about captured video clip files.
navigator.device.capture.captureVideo(
CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureVideoOptions options]
);
### Description
Starts an asynchronous operation to capture video recordings using the
device's video recording application. The operation allows the user
to capture more than one recordings in a single session.
The capture operation ends when either the user exits the video
recording application, or the maximum number of recordings specified
by `CaptureVideoOptions.limit` is reached. If no `limit` parameter
value is specified, it defaults to one (1), and the capture operation
terminates after the user records a single video clip.
When the capture operation finishes, it the `CaptureCB` callback
executes with an array of `MediaFile` objects describing each captured
video clip file. If the user terminates the operation before
capturing a video clip, the `CaptureErrorCB` callback executes with a
`CaptureError` object featuring a
`CaptureError.CAPTURE_NO_MEDIA_FILES` error code.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
### Example
// capture callback
var captureSuccess = function(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
// do something interesting with the file
}
};
// capture error callback
var captureError = function(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
// start video capture
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:2});
### BlackBerry 10 Quirks
- Cordova for BlackBerry 10 attempts to launch the __Video Recorder__ application, provided by RIM, to capture video recordings. The app receives a `CaptureError.CAPTURE_NOT_SUPPORTED` error code if the application is not installed on the device.
## CaptureVideoOptions
> Encapsulates video capture configuration options.
### Properties
- __limit__: The maximum number of video clips the device's user can capture in a single capture operation. The value must be greater than or equal to 1 (defaults to 1).
- __duration__: The maximum duration of a video clip, in seconds.
### Example
// limit capture operation to 3 video clips
var options = { limit: 3 };
navigator.device.capture.captureVideo(captureSuccess, captureError, options);
### BlackBerry 10 Quirks
- The __duration__ property is ignored, so the length of recordings can't be limited programmatically.
### iOS Quirks
- The __limit__ property is ignored. Only one video is recorded per invocation.
### Android Quirks
- Android supports an additional __quality__ property, to allow capturing video at different qualities. A value of `1` ( the default ) means high quality and value of `0` means low quality, suitable for MMS messages.
See http://developer.android.com/reference/android/provider/MediaStore.html#EXTRA_VIDEO_QUALITY for more details.
### Example ( Android w/ quality )
// limit capture operation to 1 video clip of low quality
var options = { limit: 1, quality: 0 };
navigator.device.capture.captureVideo(captureSuccess, captureError, options);
## CaptureCB
> Invoked upon a successful media capture operation.
function captureSuccess( MediaFile[] mediaFiles ) { ... };
### Description
This function executes after a successful capture operation completes.
At this point a media file has been captured, and either the user has
exited the media capture application, or the capture limit has been
reached.
Each `MediaFile` object describes a captured media file.
### Example
// capture callback
function captureSuccess(mediaFiles) {
var i, path, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
path = mediaFiles[i].fullPath;
// do something interesting with the file
}
};
## CaptureError
> Encapsulates the error code resulting from a failed media capture operation.
### Properties
- __code__: One of the pre-defined error codes listed below.
### Constants
- `CaptureError.CAPTURE_INTERNAL_ERR`: The camera or microphone failed to capture image or sound.
- `CaptureError.CAPTURE_APPLICATION_BUSY`: The camera or audio capture application is currently serving another capture request.
- `CaptureError.CAPTURE_INVALID_ARGUMENT`: Invalid use of the API (e.g., the value of `limit` is less than one).
- `CaptureError.CAPTURE_NO_MEDIA_FILES`: The user exits the camera or audio capture application before capturing anything.
- `CaptureError.CAPTURE_NOT_SUPPORTED`: The requested capture operation is not supported.
## CaptureErrorCB
> Invoked if an error occurs during a media capture operation.
function captureError( CaptureError error ) { ... };
### Description
This function executes if an error occurs when trying to launch a
media capture operation. Failure scenarios include when the capture
application is busy, a capture operation is already taking place, or
the user cancels the operation before any media files are captured.
This function executes with a `CaptureError` object containing an
appropriate error `code`.
### Example
// capture error callback
var captureError = function(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
## ConfigurationData
> Encapsulates a set of media capture parameters that a device supports.
### Description
Describes media capture modes supported by the device. The
configuration data includes the MIME type, and capture dimensions for
video or image capture.
The MIME types should adhere to [RFC2046](http://www.ietf.org/rfc/rfc2046.txt). Examples:
- `video/3gpp`
- `video/quicktime`
- `image/jpeg`
- `audio/amr`
- `audio/wav`
### Properties
- __type__: The ASCII-encoded lowercase string representing the media type. (DOMString)
- __height__: The height of the image or video in pixels. The value is zero for sound clips. (Number)
- __width__: The width of the image or video in pixels. The value is zero for sound clips. (Number)
### Example
// retrieve supported image modes
var imageModes = navigator.device.capture.supportedImageModes;
// Select mode that has the highest horizontal resolution
var width = 0;
var selectedmode;
for each (var mode in imageModes) {
if (mode.width > width) {
width = mode.width;
selectedmode = mode;
}
}
Not supported by any platform. All configuration data arrays are empty.
## MediaFile.getFormatData
> Retrieves format information about the media capture file.
mediaFile.getFormatData(
MediaFileDataSuccessCB successCallback,
[MediaFileDataErrorCB errorCallback]
);
### Description
This function asynchronously attempts to retrieve the format
information for the media file. If successful, it invokes the
`MediaFileDataSuccessCB` callback with a `MediaFileData` object. If
the attempt fails, this function invokes the `MediaFileDataErrorCB`
callback.
### Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
### Amazon Fire OS Quirks
The API to access media file format information is limited, so not all
`MediaFileData` properties are supported.
### BlackBerry 10 Quirks
Does not provide an API for information about media files, so all
`MediaFileData` objects return with default values.
### Android Quirks
The API to access media file format information is limited, so not all
`MediaFileData` properties are supported.
### iOS Quirks
The API to access media file format information is limited, so not all
`MediaFileData` properties are supported.
## MediaFile
> Encapsulates properties of a media capture file.
### Properties
- __name__: The name of the file, without path information. (DOMString)
- __fullPath__: The full path of the file, including the name. (DOMString)
- __type__: The file's mime type (DOMString)
- __lastModifiedDate__: The date and time when the file was last modified. (Date)
- __size__: The size of the file, in bytes. (Number)
### Methods
- __MediaFile.getFormatData__: Retrieves the format information of the media file.
## MediaFileData
> Encapsulates format information about a media file.
### Properties
- __codecs__: The actual format of the audio and video content. (DOMString)
- __bitrate__: The average bitrate of the content. The value is zero for images. (Number)
- __height__: The height of the image or video in pixels. The value is zero for audio clips. (Number)
- __width__: The width of the image or video in pixels. The value is zero for audio clips. (Number)
- __duration__: The length of the video or sound clip in seconds. The value is zero for images. (Number)
### BlackBerry 10 Quirks
No API provides format information for media files, so the
`MediaFileData` object returned by `MediaFile.getFormatData` features
the following default values:
- __codecs__: Not supported, and returns `null`.
- __bitrate__: Not supported, and returns zero.
- __height__: Not supported, and returns zero.
- __width__: Not supported, and returns zero.
- __duration__: Not supported, and returns zero.
### Amazon Fire OS Quirks
Supports the following `MediaFileData` properties:
- __codecs__: Not supported, and returns `null`.
- __bitrate__: Not supported, and returns zero.
- __height__: Supported: image and video files only.
- __width__: Supported: image and video files only.
- __duration__: Supported: audio and video files only
### Android Quirks
Supports the following `MediaFileData` properties:
- __codecs__: Not supported, and returns `null`.
- __bitrate__: Not supported, and returns zero.
- __height__: Supported: image and video files only.
- __width__: Supported: image and video files only.
- __duration__: Supported: audio and video files only.
### iOS Quirks
Supports the following `MediaFileData` properties:
- __codecs__: Not supported, and returns `null`.
- __bitrate__: Supported on iOS4 devices for audio only. Returns zero for images and videos.
- __height__: Supported: image and video files only.
- __width__: Supported: image and video files only.
- __duration__: Supported: audio and video files only.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-network-information
This plugin provides an implementation of an old version of the
[Network Information API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/).
It provides information about the device's cellular and
wifi connection, and whether the device has an internet connection.
## Installation
cordova plugin add cordova-plugin-network-information
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- iOS
- Windows Phone 7 and 8
- Tizen
- Windows
- Firefox OS
# Connection
> The `connection` object, exposed via `navigator.connection`, provides information about the device's cellular and wifi connection.
## Properties
- connection.type
## Constants
- Connection.UNKNOWN
- Connection.ETHERNET
- Connection.WIFI
- Connection.CELL_2G
- Connection.CELL_3G
- Connection.CELL_4G
- Connection.CELL
- Connection.NONE
## connection.type
This property offers a fast way to determine the device's network
connection state, and type of connection.
### Quick Example
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
checkConnection();
### API Change
Until Cordova 2.3.0, the `Connection` object was accessed via
`navigator.network.connection`, after which it was changed to
`navigator.connection` to match the W3C specification. It's still
available at its original location, but is deprecated and will
eventually be removed.
### iOS Quirks
- iOS can't detect the type of cellular network connection.
- `navigator.connection.type` is set to `Connection.CELL` for all cellular data.
### Windows Phone Quirks
- When running in the emulator, always detects `navigator.connection.type` as `Connection.UNKNOWN`.
- Windows Phone can't detect the type of cellular network connection.
- `navigator.connection.type` is set to `Connection.CELL` for all cellular data.
### Windows Quirks
- When running in the Phone 8.1 emulator, always detects `navigator.connection.type` as `Connection.ETHERNET`.
### Tizen Quirks
- Tizen can only detect a WiFi or cellular connection.
- `navigator.connection.type` is set to `Connection.CELL_2G` for all cellular data.
### Firefox OS Quirks
- Firefox OS can't detect the type of cellular network connection.
- `navigator.connection.type` is set to `Connection.CELL` for all cellular data.
### Browser Quirks
- Browser can't detect the type of network connection.
`navigator.connection.type` is always set to `Connection.UNKNOWN` when online.
# Network-related Events
## offline
The event fires when an application goes offline, and the device is
not connected to the Internet.
document.addEventListener("offline", yourCallbackFunction, false);
### Details
The `offline` event fires when a previously connected device loses a
network connection so that an application can no longer access the
Internet. It relies on the same information as the Connection API,
and fires when the value of `connection.type` becomes `NONE`.
Applications typically should use `document.addEventListener` to
attach an event listener once the `deviceready` event fires.
### Quick Example
document.addEventListener("offline", onOffline, false);
function onOffline() {
// Handle the offline event
}
### iOS Quirks
During initial startup, the first offline event (if applicable) takes at least a second to fire.
### Windows Phone 7 Quirks
When running in the Emulator, the `connection.status` is always unknown, so this event does _not_ fire.
### Windows Phone 8 Quirks
The Emulator reports the connection type as `Cellular`, which does not change, so the event does _not_ fire.
## online
This event fires when an application goes online, and the device
becomes connected to the Internet.
document.addEventListener("online", yourCallbackFunction, false);
### Details
The `online` event fires when a previously unconnected device receives
a network connection to allow an application access to the Internet.
It relies on the same information as the Connection API,
and fires when the `connection.type` changes from `NONE` to any other
value.
Applications typically should use `document.addEventListener` to
attach an event listener once the `deviceready` event fires.
### Quick Example
document.addEventListener("online", onOnline, false);
function onOnline() {
// Handle the online event
}
### iOS Quirks
During initial startup, the first `online` event (if applicable) takes
at least a second to fire, prior to which `connection.type` is
`UNKNOWN`.
### Windows Phone 7 Quirks
When running in the Emulator, the `connection.status` is always unknown, so this event does _not_ fire.
### Windows Phone 8 Quirks
The Emulator reports the connection type as `Cellular`, which does not change, so events does _not_ fire.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-splashscreen
This plugin displays and hides a splash screen during application launch.
## Installation
// npm hosted (new) id
cordova plugin add cordova-plugin-splashscreen
// you may also install directly from this repo
cordova plugin add https://github.com/apache/cordova-plugin-splashscreen.git
## Supported Platforms
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
- Browser
## Preferences
#### config.xml
- __SplashScreen__ (string). The resource name which is used for the displaying splash screen. Different platforms use values for this.
<preference name="SplashScreen" value="resourcename" />
- __AutoHideSplashScreen__ (boolean, default to `true`). Indicates wherether hide splash screen automatically or not. Splash screen hidden after amount of time specified in the `SplashScreenDelay` preference.
<preference name="AutoHideSplashScreen" value="true" />
- __SplashScreenDelay__ (number, default to 10000). Amount of time in milliseconds to wait before automatically hide splash screen.
<preference name="SplashScreenDelay" value="resourcename" />
### Android Quirks
In your `config.xml`, you need to add the following preferences:
<preference name="SplashScreen" value="foo" />
<preference name="SplashScreenDelay" value="10000" />
<preference name="SplashMaintainAspectRatio" value="true|false" />
Where foo is the name of the splashscreen file, preferably a 9 patch file. Make sure to add your splashcreen files to your res/xml directory under the appropriate folders. The second parameter represents how long the splashscreen will appear in milliseconds. It defaults to 3000 ms. See [Icons and Splash Screens](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html)
for more information.
"SplashMaintainAspectRatio" preference is optional. If set to true, splash screen drawable is not stretched to fit screen, but instead simply "covers" the screen, like CSS "background-size:cover". This is very useful when splash screen images cannot be distorted in any way, for example when they contain scenery or text. This setting works best with images that have large margins (safe areas) that can be safely cropped on screens with different aspect ratios.
The plugin reloads splash drawable whenever orientation changes, so you can specify different drawables for portrait and landscape orientations.
### Browser Quirks
You can use the following preferences in your `config.xml`:
<platform name="browser">
<preference name="SplashScreen" value="images/browser/splashscreen.jpg" /> <!-- defaults to "img/logo.png" -->
<preference name="SplashScreenDelay" value="10000" /> <!-- defaults to "3000" -->
<preference name="SplashScreenBackgroundColor" value="green" /> <!-- defaults to "#464646" -->
<preference name="ShowSplashScreen" value="false" /> <!-- defaults to "true" -->
<preference name="SplashScreenWidth" value="600" /> <!-- defaults to "170" -->
<preference name="SplashScreenHeight" value="300" /> <!-- defaults to "200" -->
</platform>
### iOS Quirks
- `FadeSplashScreen` (boolean, defaults to `true`): Set to `false` to
prevent the splash screen from fading in and out when its display
state changes.
<preference name="FadeSplashScreen" value="false"/>
- `FadeSplashScreenDuration` (float, defaults to `2`): Specifies the
number of seconds for the splash screen fade effect to execute.
<preference name="FadeSplashScreenDuration" value="4"/>
- `ShowSplashScreenSpinner` (boolean, defaults to `true`): Set to `false`
to hide the splash-screen spinner.
<preference name="ShowSplashScreenSpinner" value="false"/>
## Methods
- splashscreen.show
- splashscreen.hide
## splashscreen.hide
Dismiss the splash screen.
navigator.splashscreen.hide();
### BlackBerry 10, WP8, iOS Quirk
The `config.xml` file's `AutoHideSplashScreen` setting must be
`false`. To delay hiding the splash screen for two seconds, add a
timer such as the following in the `deviceready` event handler:
setTimeout(function() {
navigator.splashscreen.hide();
}, 2000);
## splashscreen.show
Displays the splash screen.
navigator.splashscreen.show();
Your application cannot call `navigator.splashscreen.show()` until the app has
started and the `deviceready` event has fired. But since typically the splash
screen is meant to be visible before your app has started, that would seem to
defeat the purpose of the splash screen. Providing some configuration in
`config.xml` will automatically `show` the splash screen immediately after your
app launch and before it has fully started and received the `deviceready`
event. See [Icons and Splash Screens](http://cordova.apache.org/docs/en/edge/config_ref_images.md.html)
for more information on doing this configuration. For this reason, it is
unlikely you need to call `navigator.splashscreen.show()` to make the splash
screen visible for app startup.
<!---
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-statusbar
StatusBar
======
> The `StatusBar` object provides some functions to customize the iOS and Android StatusBar.
## Installation
This installation method requires cordova 5.0+
cordova plugin add cordova-plugin-statusbar
Older versions of cordova can still install via the __deprecated__ id
cordova plugin add org.apache.cordova.statusbar
It is also possible to install via repo url directly ( unstable )
cordova plugin add https://github.com/apache/cordova-plugin-statusbar.git
Preferences
-----------
#### config.xml
- __StatusBarOverlaysWebView__ (boolean, defaults to true). On iOS 7, make the statusbar overlay or not overlay the WebView at startup.
<preference name="StatusBarOverlaysWebView" value="true" />
- __StatusBarBackgroundColor__ (color hex string, no default value). On iOS 7, set the background color of the statusbar by a hex string (#RRGGBB) at startup. If this value is not set, the background color will be transparent.
<preference name="StatusBarBackgroundColor" value="#000000" />
- __StatusBarStyle__ (status bar style, defaults to lightcontent). On iOS 7, set the status bar style. Available options default, lightcontent, blacktranslucent, blackopaque.
<preference name="StatusBarStyle" value="lightcontent" />
### Android Quirks
The Android 5+ guidelines specify using a different color for the statusbar than your main app color (unlike the uniform statusbar color of many iOS 7+ apps), so you may want to set the statusbar color at runtime instead via `StatusBar.backgroundColorByHexString` or `StatusBar.backgroundColorByName`. One way to do that would be:
```js
if (cordova.platformId == 'android') {
StatusBar.backgroundColorByHexString("#333");
}
```
Hiding at startup
-----------
During runtime you can use the StatusBar.hide function below, but if you want the StatusBar to be hidden at app startup, you must modify your app's Info.plist file.
Add/edit these two attributes if not present. Set **"Status bar is initially hidden"** to **"YES"** and set **"View controller-based status bar appearance"** to **"NO"**. If you edit it manually without Xcode, the keys and values are:
<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
Methods
-------
This plugin defines global `StatusBar` object.
Although in the global scope, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(StatusBar);
}
- StatusBar.overlaysWebView
- StatusBar.styleDefault
- StatusBar.styleLightContent
- StatusBar.styleBlackTranslucent
- StatusBar.styleBlackOpaque
- StatusBar.backgroundColorByName
- StatusBar.backgroundColorByHexString
- StatusBar.hide
- StatusBar.show
Properties
--------
- StatusBar.isVisible
Permissions
-----------
#### config.xml
<feature name="StatusBar">
<param name="ios-package" value="CDVStatusBar" onload="true" />
</feature>
StatusBar.overlaysWebView
=================
On iOS 7, make the statusbar overlay or not overlay the WebView.
StatusBar.overlaysWebView(true);
Description
-----------
On iOS 7, set to false to make the statusbar appear like iOS 6. Set the style and background color to suit using the other functions.
Supported Platforms
-------------------
- iOS
Quick Example
-------------
StatusBar.overlaysWebView(true);
StatusBar.overlaysWebView(false);
StatusBar.styleDefault
=================
Use the default statusbar (dark text, for light backgrounds).
StatusBar.styleDefault();
Supported Platforms
-------------------
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.styleLightContent
=================
Use the lightContent statusbar (light text, for dark backgrounds).
StatusBar.styleLightContent();
Supported Platforms
-------------------
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.styleBlackTranslucent
=================
Use the blackTranslucent statusbar (light text, for dark backgrounds).
StatusBar.styleBlackTranslucent();
Supported Platforms
-------------------
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.styleBlackOpaque
=================
Use the blackOpaque statusbar (light text, for dark backgrounds).
StatusBar.styleBlackOpaque();
Supported Platforms
-------------------
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.backgroundColorByName
=================
On iOS 7, when you set StatusBar.statusBarOverlaysWebView to false, you can set the background color of the statusbar by color name.
StatusBar.backgroundColorByName("red");
Supported color names are:
black, darkGray, lightGray, white, gray, red, green, blue, cyan, yellow, magenta, orange, purple, brown
Supported Platforms
-------------------
- iOS
- Android 5+
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.backgroundColorByHexString
=================
Sets the background color of the statusbar by a hex string.
StatusBar.backgroundColorByHexString("#C0C0C0");
CSS shorthand properties are also supported.
StatusBar.backgroundColorByHexString("#333"); // => #333333
StatusBar.backgroundColorByHexString("#FAB"); // => #FFAABB
On iOS 7, when you set StatusBar.statusBarOverlaysWebView to false, you can set the background color of the statusbar by a hex string (#RRGGBB).
On WP7 and WP8 you can also specify values as #AARRGGBB, where AA is an alpha value
Supported Platforms
-------------------
- iOS
- Android 5+
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.hide
=================
Hide the statusbar.
StatusBar.hide();
Supported Platforms
-------------------
- iOS
- Android
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.show
=================
Shows the statusbar.
StatusBar.show();
Supported Platforms
-------------------
- iOS
- Android
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
StatusBar.isVisible
=================
Read this property to see if the statusbar is visible or not.
if (StatusBar.isVisible) {
// do something
}
Supported Platforms
-------------------
- iOS
- Android
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
# Cordova Plugin Test Framework
The `cordova-plugin-test-framework` plugin does two things:
1. [Defines the interface for cordova plugins to write tests](#interface)
2. [Provides a test harness for actually running those tests](#harness)
Tests run directly inside existing cordova projects, so you can rapidly switch between testing and development. You can also be sure that your test suite is testing the exact versions of plugins and platforms that your app is using.
# TLDR; Try it
1. Use your existing cordova app, or create a new one.
2. Plugins bundle their tests using a nested plugin in a `/tests` directory. To make this interesting, add some of these plugins and their respective tests. Here are a few examples:
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git#:/tests
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git#:/tests
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation#:/tests
3. Follow the docs for [Setting up the test harness](#harness).
<a name="interface" />
## Writing Plugin Tests
### Where do tests live?
Add a directory named `tests` to the root of your plugin. Within this directory, create a nested `plugin.xml` for the tests plugin. It should have a plugin id with the form `plugin-id-tests` (e.g. the `cordova-plugin-device` plugin has the nested id `cordova-plugin-device-tests`) and should contain a `<js-module>` named `tests`. E.g:
```
<js-module src="tests/tests.js" name="tests">
</js-module>
```
For example, the `cordova-plugin-device` plugin has this nested [`plugin.xml`](https://github.com/apache/cordova-plugin-device/blob/master/tests/plugin.xml).
The `cordova-plugin-test-framework` plugin will automatically find all `tests` modules across all plugins for which the nested tests plugin is installed.
### Defining Auto Tests
Simply export a function named `defineAutoTests`, which (gasp!) defines your auto-tests when run. Use the [`jasmine-2.0`](http://jasmine.github.io/2.0/introduction.html) format. E.g.:
```
exports.defineAutoTests = function() {
describe('awesome tests', function() {
it('do something sync', function() {
expect(1).toBe(1);
...
});
it('do something async', function(done) {
setTimeout(function() {
expect(1).toBe(1);
...
done();
}, 100);
});
});
describe('more awesome tests', function() {
...
});
};
```
Note: Your tests will automatically be labeled with your plugin id, so do not prefix your test descriptions.
### Defining Manual Tests
Simply export a function named `defineManualTests`, which (gasp!) defines your manual-tests when run. Manual tests do *not* use jasmine-2.0, and success/failure results are not officially reported in any standard way. Instead, create buttons to run arbitrary javascript when clicked, and display output to user using `console` or by manipulating a provided DOM element. E.g.:
```
exports.defineManualTests = function(contentEl, createActionButton) {
createActionButton('Simple Test', function() {
console.log(JSON.stringify(foo, null, '\t'));
});
createActionButton('Complex Test', function() {
contentEl.innerHTML = ...;
});
};
```
Note: Your tests will automatically be labeled with your plugin id, so do not prefix your test descriptions.
<a name="example">
### Example
See: [`cordova-plugin-device` tests](https://github.com/apache/cordova-plugin-device/blob/master/tests/tests.js).
<a name="harness" />
## Running Plugin Tests
1. Use your existing cordova app, or create a new one.
2. Add this plugin:
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-test-framework.git
3. Change the start page in `config.xml` with `<content src="cdvtests/index.html" />` or navigate to `cdvtests/index.html` from within your app.
4. Thats it!
## FAQ
* Q: Should I add `cordova-plugin-test-framework` as a `<dependency>` of my plugin?
* A: No. The end-user should decide if they want to install the test framework, not your plugin (most users won't).
* Q: What do I do if my plugin tests must have very large assets?
* A: Don't bundle those assets with your plugin. If you can, have your tests fail gracefully if those assets don't don't exist (perhaps log a warning, perhaps fail a single asset-checking test, and skip the rest). Then, ideally download those assets automatically into local storage the first time tests run. Or create a manual test step to download and install assets. As a final alternative, split those test assets into a separate plugin, and instruct users to install that plugin to run your full test suite.
* Q: Should I ship my app with the test framework plugin installed?
* A: Not likely. If you want, you can. Then your app could even embed a link to the test page (`cdvtests/index.html`) from a help section of your app, to give end users a way to run your test suite out in the feild. That may help diagnose causes of issues within your app. Maybe.
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-vibration
This plugin aligns with the W3C vibration specification http://www.w3.org/TR/vibration/
This plugin provides a way to vibrate the device.
This plugin defines global objects including `navigator.vibrate`.
Although in the global scope, they are not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.vibrate);
}
## Installation
cordova plugin add cordova-plugin-vibration
## Supported Platforms
navigator.vibrate,<br />
navigator.notification.vibrate
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 7 and 8
- Windows (Windows Phone 8.1 devices only)
navigator.notification.vibrateWithPattern<br />
navigator.notification.cancelVibration
- Android
- Windows Phone 8
- Windows (Windows Phone 8.1 devices only)
## vibrate (recommended)
This function has three different functionalities based on parameters passed to it.
###Standard vibrate
Vibrates the device for a given amount of time.
navigator.vibrate(time)
or
navigator.vibrate([time])
-__time__: Milliseconds to vibrate the device. _(Number)_
####Example
// Vibrate for 3 seconds
navigator.vibrate(3000);
// Vibrate for 3 seconds
navigator.vibrate([3000]);
####iOS Quirks
- __time__: Ignores the specified time and vibrates for a pre-set amount of time.
navigator.vibrate(3000); // 3000 is ignored
####Windows and Blackberry Quirks
- __time__: Max time is 5000ms (5s) and min time is 1ms
navigator.vibrate(8000); // will be truncated to 5000
###Vibrate with a pattern (Android and Windows only)
Vibrates the device with a given pattern
navigator.vibrate(pattern);
- __pattern__: Sequence of durations (in milliseconds) for which to turn on or off the vibrator. _(Array of Numbers)_
####Example
// Vibrate for 1 second
// Wait for 1 second
// Vibrate for 3 seconds
// Wait for 1 second
// Vibrate for 5 seconds
navigator.vibrate([1000, 1000, 3000, 1000, 5000]);
####Windows Phone 8 Quirks
- vibrate(pattern) falls back on vibrate with default duration
####Windows Quirks
- vibrate(pattern) falls back on vibrate with default duration
###Cancel vibration (not supported in iOS)
Immediately cancels any currently running vibration.
navigator.vibrate(0)
or
navigator.vibrate([])
or
navigator.vibrate([0])
Passing in a parameter of 0, an empty array, or an array with one element of value 0 will cancel any vibrations.
## *notification.vibrate (deprecated)
Vibrates the device for a given amount of time.
navigator.notification.vibrate(time)
- __time__: Milliseconds to vibrate the device. _(Number)_
### Example
// Vibrate for 2.5 seconds
navigator.notification.vibrate(2500);
### iOS Quirks
- __time__: Ignores the specified time and vibrates for a pre-set amount of time.
navigator.notification.vibrate();
navigator.notification.vibrate(2500); // 2500 is ignored
## *notification.vibrateWithPattern (deprecated)
Vibrates the device with a given pattern.
navigator.notification.vibrateWithPattern(pattern, repeat)
- __pattern__: Sequence of durations (in milliseconds) for which to turn on or off the vibrator. _(Array of Numbers)_
- __repeat__: Optional index into the pattern array at which to start repeating (will repeat until canceled), or -1 for no repetition (default). _(Number)_
### Example
// Immediately start vibrating
// vibrate for 100ms,
// wait for 100ms,
// vibrate for 200ms,
// wait for 100ms,
// vibrate for 400ms,
// wait for 100ms,
// vibrate for 800ms,
// (do not repeat)
navigator.notification.vibrateWithPattern([0, 100, 100, 200, 100, 400, 100, 800]);
## *notification.cancelVibration (deprecated)
Immediately cancels any currently running vibration.
navigator.notification.cancelVibration()
*Note - due to alignment with w3c spec, the starred methods will be phased out
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-whitelist
This plugin implements a whitelist policy for navigating the application webview on Cordova 4.0
## Supported Cordova Platforms
* Android 4.0.0 or above
* iOS 4.0.0 or above
## Navigation Whitelist
Controls which URLs the WebView itself can be navigated to. Applies to
top-level navigations only.
Quirks: on Android it also applies to iframes for non-http(s) schemes.
By default, navigations only to `file://` URLs, are allowed. To allow others URLs, you must add `<allow-navigation>` tags to your `config.xml`:
<!-- Allow links to example.com -->
<allow-navigation href="http://example.com/*" />
<!-- Wildcards are allowed for the protocol, as a prefix
to the host, or as a suffix to the path -->
<allow-navigation href="*://*.example.com/*" />
<!-- A wildcard can be used to whitelist the entire network,
over HTTP and HTTPS.
*NOT RECOMMENDED* -->
<allow-navigation href="*" />
<!-- The above is equivalent to these three declarations -->
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="data:*" />
## Intent Whitelist
Controls which URLs the app is allowed to ask the system to open.
By default, no external URLs are allowed.
On Android, this equates to sending an intent of type BROWSEABLE.
This whitelist does not apply to plugins, only hyperlinks and calls to `window.open()`.
In `config.xml`, add `<allow-intent>` tags, like this:
<!-- Allow links to web pages to open in a browser -->
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<!-- Allow links to example.com to open in a browser -->
<allow-intent href="http://example.com/*" />
<!-- Wildcards are allowed for the protocol, as a prefix
to the host, or as a suffix to the path -->
<allow-intent href="*://*.example.com/*" />
<!-- Allow SMS links to open messaging app -->
<allow-intent href="sms:*" />
<!-- Allow tel: links to open the dialer -->
<allow-intent href="tel:*" />
<!-- Allow geo: links to open maps -->
<allow-intent href="geo:*" />
<!-- Allow all unrecognized URLs to open installed apps
*NOT RECOMMENDED* -->
<allow-intent href="*" />
## Network Request Whitelist
Controls which network requests (images, XHRs, etc) are allowed to be made (via cordova native hooks).
Note: We suggest you use a Content Security Policy (see below), which is more secure. This whitelist is mostly historical for webviews which do not support CSP.
In `config.xml`, add `<access>` tags, like this:
<!-- Allow images, xhrs, etc. to google.com -->
<access origin="http://google.com" />
<access origin="https://google.com" />
<!-- Access to the subdomain maps.google.com -->
<access origin="http://maps.google.com" />
<!-- Access to all the subdomains on google.com -->
<access origin="http://*.google.com" />
<!-- Enable requests to content: URLs -->
<access origin="content:///*" />
<!-- Don't block any requests -->
<access origin="*" />
Without any `<access>` tags, only requests to `file://` URLs are allowed. However, the default Cordova application includes `<access origin="*">` by default.
Quirk: Android also allows requests to https://ssl.gstatic.com/accessibility/javascript/android/ by default, since this is required for TalkBack to function properly.
### Content Security Policy
Controls which network requests (images, XHRs, etc) are allowed to be made (via webview directly).
On Android and iOS, the network request whitelist (see above) is not able to filter all types of requests (e.g. `<video>` & WebSockets are not blocked). So, in addition to the whitelist, you should use a [Content Security Policy](http://content-security-policy.com/) `<meta>` tag on all of your pages.
On Android, support for CSP within the system webview starts with KitKat (but is available on all versions using Crosswalk WebView).
Here are some example CSP declarations for your `.html` pages:
<!-- Good default declaration:
* gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
* https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
* Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
* Enable inline JS: add 'unsafe-inline' to default-src
* Enable eval(): add 'unsafe-eval' to default-src
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">
<!-- Allow requests to foo.com -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com">
<!-- Enable all requests, inline styles, and eval() -->
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
<!-- Allow XHRs via https only -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' https:">
<!-- Allow iframe to https://cordova.apache.org/ -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">
cordova-labs plugins branch
-------------------------------
This branch stores plugins that are built by the Cordova team, but are not supported as "core" plugins.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment