Table of Contents generated with DocToc
- cordova-plugin-battery-status
- cordova-plugin-camera
- cordova-plugin-console
- cordova-plugin-contacts
- cordova-plugin-device
- cordova-plugin-device-motion
- cordova-plugin-device-orientation
- cordova-plugin-dialogs
- cordova-plugin-file
- cordova-plugin-file-transfer
- FileTransfer
- Properties
- Methods
- upload
- FileUploadResult
- download
- abort
- FileTransferError
- Backwards Compatibility Notes cordova-plugin-geolocation
- Installation
- Supported Platforms
- Methods
- Objects (Read-Only)
- navigator.geolocation.getCurrentPosition
- navigator.geolocation.watchPosition
- geolocationOptions
- navigator.geolocation.clearWatch
- Position
- Coordinates
- PositionError
- Installation
- Objects
- Methods
- navigator.globalization.getPreferredLanguage
- navigator.globalization.getLocaleName
- navigator.globalization.dateToString
- navigator.globalization.getCurrencyPattern
- navigator.globalization.getDateNames
- navigator.globalization.getDatePattern
- navigator.globalization.getFirstDayOfWeek
- navigator.globalization.getNumberPattern
- navigator.globalization.isDayLightSavingsTime
- navigator.globalization.numberToString
- navigator.globalization.stringToDate
- navigator.globalization.stringToNumber
- GlobalizationError
- Installation
- cordova.InAppBrowser.open
- InAppBrowser
- addEventListener
- removeEventListener
- close
- show
- executeScript
- insertCSS
- Usage: cordova-plugin-media
- Installation
- Supported Platforms
- Windows Phone Quirks
- Media
- media.getCurrentPosition
- media.getDuration
- media.pause
- media.play
- media.release
- media.seekTo
- media.setVolume
- media.startRecord
- media.stop
- media.stopRecord
- MediaError
- Installation
- Supported Platforms
- Objects
- Methods
- Properties
- capture.captureAudio
- CaptureAudioOptions
- capture.captureImage
- CaptureImageOptions
- capture.captureVideo
- CaptureVideoOptions
- CaptureCB
- CaptureError
- CaptureErrorCB
- ConfigurationData
- MediaFile.getFormatData
- MediaFile
- MediaFileData
- Installation
- Supported Platforms
- Connection
- Network-related Events
- StatusBar
- StatusBar.overlaysWebView
- StatusBar.styleDefault
- StatusBar.styleLightContent
- StatusBar.styleBlackTranslucent
- StatusBar.styleBlackOpaque
- StatusBar.backgroundColorByName
- StatusBar.backgroundColorByHexString
- StatusBar.hide
- StatusBar.show
- StatusBar.isVisible
- Cordova Plugin Test Framework
- TLDR; Try it
- Writing Plugin Tests
- Running Plugin Tests
- FAQ cordova-plugin-vibration
- Installation
- Supported Platforms
- vibrate (recommended)
- *notification.vibrate (deprecated)
- *notification.vibrateWithPattern (deprecated)
- *notification.cancelVibration (deprecated) cordova-plugin-whitelist
- Supported Cordova Platforms
- Navigation Whitelist
- Intent Whitelist
- Network Request Whitelist
- cordova-labs plugins branch
<!--
-->
This plugin provides an implementation of an old version of the Battery Status Events API.
It adds the following three window
events:
- batterystatus
- batterycritical
- batterylow
cordova plugin add cordova-plugin-battery-status
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.
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Windows Phone 7 and 8
- Windows (Windows Phone 8.1 only)
- Tizen
- Firefox OS
- Browser
- Warning: the Android + Fire OS implementations are greedy and prolonged use will drain the user's battery.
Windows Phone 7 does not provide native APIs to determine battery
level, so the level
property is unavailable. The isPlugged
parameter is supported.
Windows Phone 8.1 does not support isPlugged
parameter.
The level
parameter is supported.
Supported browsers are Chrome, Firefox and Opera.
window.addEventListener("batterystatus", onBatteryStatus, false);
function onBatteryStatus(info) {
// Handle the online event
console.log("Level: " + info.level + " isPlugged: " + info.isPlugged);
}
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.
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Tizen
- Firefox OS
- Windows (Windows Phone 8.1 only)
- Browser
Windows Phone 8.1 will fire batterycritical
event regardless of plugged state as it is not supported.
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
Supported browsers are Chrome, Firefox and Opera.
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.
- Amazon Fire OS
- iOS
- Android
- BlackBerry 10
- Tizen
- Firefox OS
- Windows (Windows Phone 8.1 only)
- Browser
Windows Phone 8.1 will fire batterylow
event regardless of plugged state as it is not supported.
window.addEventListener("batterylow", onBatteryLow, false);
function onBatteryLow(info) {
// Handle the battery low event
alert("Battery Level Low " + info.level + "%");
}
Supported browsers are Chrome, Firefox and Opera.
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);
}
cordova plugin add cordova-plugin-camera
- Camera
- navigator.camera.getPicture(success, fail, options)
- CameraOptions
- CameraPopoverHandle
- CameraPopoverOptions
- navigator.camera.cleanup
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);
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, 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
.
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);
}
-
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 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 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.
Can only return photos as base64-encoded image.
Camera plugin is currently implemented using Web Activities.
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);
Invoking the native camera application while the device is connected via Zune does not work, and triggers an error callback.
Tizen only supports a destinationType
of
Camera.DestinationType.FILE_URI
and a sourceType
of
Camera.PictureSourceType.PHOTOLIBRARY
.
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
isPHOTOLIBRARY
orSAVEDPHOTOALBUM
. Defined innagivator.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 };
-
Any
cameraDirection
value results in a back-facing photo. -
Ignores the
allowEdit
parameter. -
Camera.PictureSourceType.PHOTOLIBRARY
andCamera.PictureSourceType.SAVEDPHOTOALBUM
both display the same photo album.
-
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
andCamera.PictureSourceType.SAVEDPHOTOALBUM
both display the same photo album.
-
Ignores the
quality
parameter. -
Ignores the
allowEdit
parameter. -
Camera.MediaType
is not supported. -
Ignores the
correctOrientation
parameter. -
Ignores the
cameraDirection
parameter.
-
Ignores the
quality
parameter. -
Camera.DestinationType
is ignored and equals1
(image file URI) -
Ignores the
allowEdit
parameter. -
Ignores the
PictureSourceType
parameter (user chooses it in a dialog window) -
Ignores the
encodingType
-
Ignores the
targetWidth
andtargetHeight
-
Camera.MediaType
is not supported. -
Ignores the
correctOrientation
parameter. -
Ignores the
cameraDirection
parameter.
- 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.
-
options not supported
-
always returns a FILE URI
-
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 You may also comment or up-vote the related issue in the issue tracker -
Ignores the
mediaType
property ofcameraOptions
as the Windows Phone SDK does not provide a way to choose videos from PHOTOLIBRARY.
onError callback function that provides an error message.
function(message) {
// Show a helpful message
}
- message: The message is provided by the device's native code. (String)
onSuccess callback function that provides the image data.
function(imageData) {
// Do something with the image
}
- imageData: Base64 encoding of the image data, or the image file URI, depending on
cameraOptions
in effect. (String)
// Show image
//
function cameraCallback(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}
A handle to the popover dialog created by navigator.camera.getPicture
.
- setPosition: Set the position of the popover. Takes the
CameraPopoverOptions
that specify the new position.
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);
}
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
};
-
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.
Removes intermediate photos taken by the camera from temporary storage.
navigator.camera.cleanup( cameraSuccess, cameraError );
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
.
navigator.camera.cleanup(onSuccess, onFail);
function onSuccess() {
console.log("Camera cleanup success.")
}
function onFail(message) {
alert('Failed because: ' + message);
}
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");
}
cordova plugin add cordova-plugin-console
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.
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
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.
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
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()
.
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.
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
Create www/manifest.webapp as described in Manifest Docs. Add relevant permisions. There is also a need to change the webapp type to "privileged" - Manifest Docs. WARNING: All privileged apps enforce Content Security Policy 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"
}
}
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 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.create
- navigator.contacts.find
- navigator.contacts.pickContact
- Contact
- ContactName
- ContactField
- ContactAddress
- ContactOrganization
- ContactFindOptions
- ContactError
- ContactFieldType
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.
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
var myContact = navigator.contacts.create({"displayName": "Test User"});
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.
-
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
)
-
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows (Windows Phone 8.1 and Windows 10)
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);
__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.
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.
-
contactSuccess: Success callback function invoked with the single Contact object. [Required]
-
contactError: Error callback function, invoked when an error occurs. [Optional]
- Android
- iOS
- Windows Phone 8
- Windows 8
- Windows
navigator.contacts.pickContact(function(contact){
console.log('The following contact has been selected:' + JSON.stringify(contact));
},function(err){
console.log('Error: ' + err);
});
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.
-
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[])
-
clone: Returns a new
Contact
object that is a deep copy of the calling object, with theid
property set tonull
. -
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.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
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 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);
function onSuccess() {
alert("Removal Success");
};
function onError(contactError) {
alert("Error = " + contactError.code);
};
// remove the contact from the device
contact.remove(onSuccess,onError);
- categories: Not supported on Android 2.X devices, returning
null
.
- id: Assigned by the device when saving the contact.
-
categories: Partially supported. Fields pref and type are returning
null
-
ims: Not supported
-
photos: Not supported
-
displayName: Not supported on iOS, returning
null
unless there is noContactName
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
.
-
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
-
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.
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.
-
pref: Set to
true
if thisContactAddress
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)
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
// 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);
- pref: Not supported, returning
false
on Android 2.X devices.
-
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.
- formatted: Currently not supported
-
pref: Not supported on iOS devices, returning
false
. -
formatted: Currently not supported.
- pref: Not supported
- pref: Not supported
The ContactError
object is returned to the user through the
contactError
callback function when an error occurs.
- code: One of the predefined error codes listed below.
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)
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.
-
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 thisContactField
contains the user's preferred value. (boolean)
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
// 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();
- pref: Not supported, returning
false
.
-
type: Partially supported. Used for phone numbers.
-
value: Supported.
-
pref: Not supported, returning
false
.
- pref: Not supported, returning
false
.
- pref: Not supported, returning
false
.
- pref: Not supported, returning
false
.
Contains different kinds of information about a Contact
object's name.
-
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)
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
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);
- formatted: Partially supported, and read-only. Returns a concatenation of
honorificPrefix
,givenName
,middleName
,familyName
, andhonorificSuffix
.
-
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
.
- formatted: Partially supported, and read-only. Returns a concatenation of
honorificPrefix
,givenName
,middleName
,familyName
, andhonorificSuffix
.
- formatted: Partially supported. Returns iOS Composite Name, but is read-only.
-
formatted: This is the only name property, and is identical to
displayName
, andnickname
-
familyName: not supported
-
givenName: not supported
-
middleName: not supported
-
honorificPrefix: not supported
-
honorificSuffix: not supported
- formatted: It is identical to
displayName
The ContactOrganization
object stores a contact's organization
properties. A Contact
object stores one or more
ContactOrganization
objects in an array.
-
pref: Set to
true
if thisContactOrganization
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)
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows (Windows 8.1 and Windows Phone 8.1 devices only)
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);
- pref: Not supported by Android 2.X devices, returning
false
.
-
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.
-
pref: Not supported
-
type: Not supported
-
department: Not supported
-
Fields name and title stored in org and jobTitle.
-
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.
-
pref: Not supported, returning
false
. -
type: Not supported, returning
null
.
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);
}
cordova plugin add cordova-plugin-device
- device.cordova
- device.model
- device.platform
- device.uuid
- device.version
Get the version of Cordova running on the device.
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
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.
- Android
- BlackBerry 10
- Browser
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
// 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;
- Gets the product name instead of the model name, which is often the production code name. For example, the Nexus One returns
Passion
, and Motorola Droid returnsvoles
.
- Returns the device model assigned by the vendor, for example,
TIZEN
- Returns the device model specified by the manufacturer. For example, the Samsung Focus returns
SGH-i917
.
Get the device's operating system name.
var string = device.platform;
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
// 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 devices report the platform as WinCE
.
Windows Phone 8 devices report the platform as Win32NT
.
Get the device's Universally Unique Identifier (UUID).
var string = device.uuid;
The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model.
- Android
- BlackBerry 10
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
// 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;
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.
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.
Get the operating system version.
var string = device.version;
- Android 2.1+
- BlackBerry 10
- Browser
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
// 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;
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);
}
cordova plugin add cordova-plugin-device-motion
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 8
- Windows
- navigator.accelerometer.getCurrentAcceleration
- navigator.accelerometer.watchAcceleration
- navigator.accelerometer.clearWatch
- Acceleration
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);
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);
Values for X, Y, Z motion are all randomly generated in order to simulate the accelerometer.
-
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 awatchAccelerometer
call.
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)
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);
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.
Stop watching the Acceleration
referenced by the watchID
parameter.
navigator.accelerometer.clearWatch(watchID);
- watchID: The ID returned by
navigator.accelerometer.watchAcceleration
.
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
// ... later on ...
navigator.accelerometer.clearWatch(watchID);
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
.
- 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)
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);
}
cordova plugin add cordova-plugin-device-orientation
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8 (if available in hardware)
- Windows 8
- navigator.compass.getCurrentHeading
- navigator.compass.watchHeading
- navigator.compass.clearWatch
Get the current compass heading. The compass heading is returned via a CompassHeading
object using the compassSuccess
callback function.
navigator.compass.getCurrentHeading(compassSuccess, compassError);
function onSuccess(heading) {
alert('Heading: ' + heading.magneticHeading);
};
function onError(error) {
alert('CompassError: ' + error.code);
};
navigator.compass.getCurrentHeading(onSuccess, onError);
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)
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);
Values for current heading are randomly generated in order to simulate the compass.
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.
filter
is not supported.
- No support for
filter
.
- No support for
filter
.
- No support for
filter
.
- No support for
filter
.
Stop watching the compass referenced by the watch ID parameter.
navigator.compass.clearWatch(watchID);
- watchID: The ID returned by
navigator.compass.watchHeading
.
var watchID = navigator.compass.watchHeading(onSuccess, onError, options);
// ... later on ...
navigator.compass.clearWatch(watchID);
A CompassHeading
object is returned to the compassSuccess
callback function.
-
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)
-
trueHeading
is not supported, but reports the same value asmagneticHeading
-
headingAccuracy
is always 0 because there is no difference between themagneticHeading
andtrueHeading
-
The
trueHeading
property is not supported, but reports the same value asmagneticHeading
. -
The
headingAccuracy
property is always 0 because there is no difference between themagneticHeading
andtrueHeading
.
-
The
trueHeading
property is not supported, but reports the same value asmagneticHeading
. -
The
headingAccuracy
property is always 0 because there is no difference between themagneticHeading
andtrueHeading
.
-
The
trueHeading
property is only returned for location services enabled vianavigator.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.
A CompassError
object is returned to the compassError
callback function when an error occurs.
- code: One of the predefined error codes listed below.
CompassError.COMPASS_INTERNAL_ERR
CompassError.COMPASS_NOT_SUPPORTED
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);
}
cordova plugin add cordova-plugin-dialogs
navigator.notification.alert
navigator.notification.confirm
navigator.notification.prompt
navigator.notification.beep
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
)
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows
-
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
andconfirm
are non-blocking calls, results of which are only available asynchronously.
Both native-blocking window.alert()
and non-blocking navigator.notification.alert()
are available.
navigator.notification.alert('text', callback, 'title', 'text')
callback parameter is passed the number 1.
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
])
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.
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
);
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows
-
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
andconfirm
are non-blocking, so the result is only available asynchronously.
-
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.
Both native-blocking window.confirm()
and non-blocking navigator.notification.confirm()
are available.
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)
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)
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
);
- Amazon Fire OS
- Android
- Firefox OS
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
-
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.
- On Windows prompt dialog is html-based due to lack of such native api.
Both native-blocking window.prompt()
and non-blocking navigator.notification.prompt()
are available.
The device plays a beep sound.
navigator.notification.beep(times);
- times: The number of times to repeat the beep. (Number)
// Beep twice!
navigator.notification.beep(2);
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Amazon Fire OS plays the default Notification Sound specified under the Settings/Display & Sound panel.
- Android plays the default Notification ringtone specified under the Settings/Sound & Display panel.
- Relies on a generic beep file from the Cordova distribution.
-
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 namedbeep.wav
.
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/
The (now-defunct) Directories and System extensions Latest: 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/
It also implements the FileWriter spec : http://dev.w3.org/2009/dap/file-system/file-writer.html
For usage, please refer to HTML5 Rocks' excellent FileSystem article.
For an overview of other storage options, refer to Cordova's storage guide.
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);
}
cordova plugin add cordova-plugin-file
- 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)
.
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)
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.
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 |
appname.app/ |
applicationDirectory | bundle | r | N/A | N/A | N/A | Yes |
www/ |
- | - | r | N/A | N/A | N/A | Yes |
Documents/ |
documentsDirectory | documents | r/w | Yes | No | Yes | Yes |
NoCloud/ |
- | documents-nosync | r/w | Yes | No | No | Yes |
Library |
- | library | r/w | Yes | No | Yes? | Yes |
NoCloud/ |
dataDirectory | library-nosync | r/w | Yes | No | No | Yes |
Cloud/ |
syncedDataDirectory | - | r/w | Yes | No | Yes | Yes |
Caches/ |
cacheDirectory | cache | r/w | Yes* | Yes*** | No | Yes |
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.
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 |
cache |
cacheDirectory | cache | r/w | Yes | Yes* | Yes |
files |
dataDirectory | files | r/w | Yes | No | Yes |
Documents |
documents | r/w | Yes | No | Yes | |
<sdcard>/ |
externalRootDirectory | sdcard | r/w | Yes | No | No |
Android/data/<app-id>/ |
externalApplicationStorageDirectory | - | r/w | Yes | No | No |
cache |
externalCacheDirectry | cache-external | r/w | Yes | No** | No |
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
.
Device Path | cordova.file.* |
r/w? | persistent? | OS clears | private |
---|---|---|---|---|---|
file:///accounts/1000/appdata/<app id>/ |
applicationStorageDirectory | r | N/A | N/A | Yes |
app/native |
applicationDirectory | r | N/A | N/A | Yes |
data/webviews/webfs/temporary/local__0 |
cacheDirectory | r/w | No | Yes | Yes |
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.
Device Path | cordova.file.* |
iosExtraFileSystems |
r/w? | OS clears | private |
---|---|---|---|---|---|
/Applications/<appname>.app/ |
- | bundle | r | N/A | Yes |
Content/Resources/ |
applicationDirectory | - | r | N/A | Yes |
~/Library/Application Support/<bundle-id>/ |
applicationStorageDirectory | - | r/w | No | Yes |
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.
There are multiple valid locations to store persistent files on an Android device. See this page 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.
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).
cordova.file.applicationStorageDirectory
is read-only; attempting to store files within the root directory will fail. Use one of the othercordova.file.*
properties defined for iOS (onlyapplicationDirectory
andapplicationStorageDirectory
are read-only).FileReader.readAsText(blob, encoding)
- The
encoding
parameter is not supported, and UTF-8 encoding is always in effect.
- The
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.
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
andmoveTo
do not support directories
The following data paths are supported:
applicationDirectory
- Usesxhr
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).
- 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 viacdvfile
. - The plugin does not follow "File System API 8.3 Naming restrictions".
- Blob and File'
close
function is not supported. FileSaver
andBlobBuilder
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 astext-plain
according the specification), the mediatype in Firefox is alwaysapplication/octet-stream
. For example, if the content isabcdefg
then Firefox returnsdata:application/octet-stream;base64,YWJjZGVmZw==
, IE returnsdata:;base64,YWJjZGVmZw==
, Chrome returnsdata:<mediatype depending on extension of entry name>;base64,YWJjZGVmZw==
.toInternalURL
returns the path in the formfile:///persistent/path/to/entry
(Firefox, IE). Chrome returns the path in the formcdvfile://localhost/persistent/file
.
- Chrome filesystem is not immediately ready after device ready event. As a workaround you can subscribe to
filePluginIsReady
event. Example:
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 viafile:///
protocol. File
object will be not changed if you use flag{create:true}
when getting an existingEntry
.- events
cancelable
property is set to true in Chrome. This is contrary to the specification. toURL
function in Chrome returnsfilesystem:
-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 inboundurl
to havefilesystem
prefix. For example,url
parameter forresolveLocalFileSystemURL
should be in the formfilesystem:file:///persistent/somefile.txt
as opposed to the formfile:///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.
.
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 forrequestFileSystem
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 supportsmodificationTime
field change only.copyTo
andmoveTo
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
andtruncate
functions are not supported.- progress events are not fired. For example, this handler will be not executed:
writer.onprogress = function() { /*commands*/ };
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.
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, File System Layouts and Configuring the Plugin 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:
<img src="cdvfile://localhost/persistent/img/logo.png" />
*Note: This method requires following Content Security rules updates:
- Add
cdvfile:
scheme toContent-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://*" />
toconfig.xml
.
Converting cdvfile:// to native path
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://
resolveLocalFileSystemURL(nativePath, function(entry) {
console.log('cdvfile URI: ' + entry.toInternalURL());
Using cdvfile in core plugins
fileTransfer.download(uri, 'cdvfile://localhost/temporary/path/to/file.mp3', function (entry) { ...
var my_media = new Media('cdvfile://localhost/temporary/path/to/file.mp3', ...);
my_media.play();
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 |
The set of available filesystems can be configured per-platform. Both iOS and
Android recognize a 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" />
files
: The application's internal file storage directoryfiles-external
: The application's external file storage directorysdcard
: The global external file storage directory (this is the root of the SD card, if one is installed). You must have theandroid.permission.WRITE_EXTERNAL_STORAGE
permission to use this.cache
: The application's internal cache directorycache-external
: The application's external cache directoryroot
: The entire device filesystem
Android also supports a special filesystem named "documents", which represents a "/Documents/" subdirectory within the "files" filesystem.
library
: The application's Library directorydocuments
: The application's Documents directorycache
: The application's Cache directorybundle
: 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.
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);
}
cordova plugin add cordova-plugin-file-transfer
- 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
The FileTransfer
object provides a way to upload files using an HTTP
multi-part POST or PUT request, and to download files as well.
- onprogress: Called with a
ProgressEvent
whenever a new chunk of data is transferred. (Function)
-
upload: sends a file to a server.
-
download: downloads a file from server.
-
abort: Aborts an in-progress transfer.
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 aFileTransferError
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
orPOST
. Defaults toPOST
. (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)
- fileKey: The name of the form element. Defaults to
-
trustAllHosts: Optional parameter, defaults to
false
. If set totrue
, 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)
// !! 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);
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);
A FileUploadResult
object is passed to the success callback of the
FileTransfer
object's upload()
method.
-
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.
- Does not support
responseCode
orbytesSent
.
- withCredentials: boolean that tells the browser to set the withCredentials flag on the XMLHttpRequest
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 aFileTransferError
object. (Function) -
trustAllHosts: Optional parameter, defaults to
false
. If set totrue
, 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).
// !! 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=="
}
}
);
- Download requests is being cached by native implementation. To avoid caching, pass
if-Modified-Since
header to download method.
- withCredentials: boolean that tells the browser to set the withCredentials flag on the XMLHttpRequest
Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object which has an error code of FileTransferError.ABORT_ERR.
// !! 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();
A FileTransferError
object is passed to an error callback when an error occurs.
-
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)
- 1 =
FileTransferError.FILE_NOT_FOUND_ERR
- 2 =
FileTransferError.INVALID_URL_ERR
- 3 =
FileTransferError.CONNECTION_ERR
- 4 =
FileTransferError.ABORT_ERR
- 5 =
FileTransferError.NOT_MODIFIED_ERR
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.
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, 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");
}
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
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows
- navigator.geolocation.getCurrentPosition
- navigator.geolocation.watchPosition
- navigator.geolocation.clearWatch
- Position
- PositionError
- Coordinates
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]);
-
geolocationSuccess: The callback that is passed the current position.
-
geolocationError: (Optional) The callback that executes if an error occurs.
-
geolocationOptions: (Optional) The geolocation options.
// 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);
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]);
-
geolocationSuccess: The callback that is passed the current position.
-
geolocationError: (Optional) The callback that executes if an error occurs.
-
geolocationOptions: (Optional) The geolocation options.
- 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.
// 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 });
Optional parameters to customize the retrieval of the geolocation
Position
.
{ maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };
-
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 totrue
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
orgeolocation.watchPosition
until the correspondinggeolocationSuccess
callback executes. If thegeolocationSuccess
callback is not invoked within this time, thegeolocationError
callback is passed aPositionError.TIMEOUT
error code. (Note that when used in conjunction withgeolocation.watchPosition
, thegeolocationError
callback could be called on an interval everytimeout
milliseconds!) (Number) -
maximumAge: Accept a cached position whose age is no greater than the specified time in milliseconds. (Number)
Android 2.x emulators do not return a geolocation result unless the enableHighAccuracy
option is set to true
.
Stop watching for changes to the device's location referenced by the
watchID
parameter.
navigator.geolocation.clearWatch(watchID);
- watchID: The id of the
watchPosition
interval to clear. (String)
// 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);
Contains Position
coordinates and timestamp, created by the geolocation API.
-
coords: A set of geographic coordinates. (Coordinates)
-
timestamp: Creation timestamp for
coords
. (Date)
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.
-
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)
altitudeAccuracy: Not supported by Android devices, returning null
.
altitudeAccuracy: Not supported by Android devices, returning null
.
The PositionError
object is passed to the geolocationError
callback function when an error occurs with navigator.geolocation.
-
code: One of the predefined error codes listed below.
-
message: Error message describing the details of the error encountered.
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 ingeolocationOptions
. When used withnavigator.geolocation.watchPosition
, this error could be repeatedly passed to thegeolocationError
callback everytimeout
milliseconds.
- Returned when the device is unable to retrieve a position within the time specified by the
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);
}
cordova plugin add cordova-plugin-globalization
- GlobalizationError
- 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
Get the BCP 47 language tag for the client's current language.
navigator.globalization.getPreferredLanguage(successCallback, errorCallback);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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');}
);
- 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"
- 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.
- 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.
- Falls back on getLocaleName
Returns the BCP 47 compliant tag for the client's current locale setting.
navigator.globalization.getLocaleName(successCallback, errorCallback);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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');}
);
- Java does not distinguish between a set "langauge" and set "locale," so this
method is essentially the same as
navigator.globalizatin.getPreferredLanguage()
.
- 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.
- 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.
- IE returns the locale of operating system. Chrome and Firefox return browser language tag.
Returns a date formatted as a string according to the client's locale and timezone.
navigator.globalization.dateToString(date, successCallback, errorCallback, options);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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' }
);
formatLength
options are a subset of Unicode UTS #35. The default optionshort
depends on a user selected date format withinSettings -> System -> Date & time -> Choose date format
, which provide ayear
pattern only with 4 digits, not 2 digits. This means that it is not completely aligned with ICU.
-
The
formatLength
option supports onlyshort
andfull
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.
-
The
formatLength
option supports onlyshort
andfull
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.
-
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 supportsfull
andshort
formatLength only.
formatLength
is not distinguishinglong
andfull
- only one method of displaying date (no
long
orfull
version)
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);
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. (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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows 8
- Windows
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: ,
- Only 'code' and 'fraction' properties are supported
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);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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' }
);
options.type
supports agenitive
value, important for some languages
- The array of months contains 13 elements.
- The returned array may be not completely aligned with ICU depending on a user locale.
- The array of months contains 12 elements.
- The returned array may be not completely aligned with ICU depending on a user locale.
- Date names are not completely aligned with ICU
- The array of months contains 12 elements.
Returns a pattern string to format and parse dates according to the client's user preferences.
navigator.globalization.getDatePattern(successCallback, errorCallback, options);
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. (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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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' }
);
}
-
The
formatLength
supports onlyshort
andfull
values. -
The
pattern
fordate 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.
-
The
formatLength
supports onlyshort
andfull
values. -
The
pattern
fordate 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.
-
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.
Returns the first day of the week according to the client's user preferences and calendar.
navigator.globalization.getFirstDayOfWeek(successCallback, errorCallback);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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');}
);
- On Windows 8.0/8.1 the value depends on user' calendar preferences. On Windows Phone 8.1 the value depends on current locale.
- Only 79 locales are supported because moment.js is used in this method.
Returns a pattern string to format and parse numbers according to the client's user preferences.
navigator.globalization.getNumberPattern(successCallback, errorCallback, options);
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. (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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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: ,
-
The
pattern
property is not supported, and returns an empty string. -
The
fraction
property is not supported, and returns zero.
- The
pattern
property is not supported, and returns an empty string.
- getNumberPattern is supported in Chrome only; the only defined property is
pattern
.
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);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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');}
);
Returns a number formatted as a string according to the client's user preferences.
navigator.globalization.numberToString(number, successCallback, errorCallback, options);
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'.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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 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.
currency
type is not supported.
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);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
- Browser
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'}
);
-
The
formatLength
option supports onlyshort
andfull
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.
-
The
formatLength
option supports onlyshort
andfull
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.
-
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 supportsfull
andshort
formatLength only.
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);
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
.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 8
- Windows 8
- Windows
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'}
);
- In case of
percent
type the returned value is not divided by 100.
-
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.
An object representing a error from the Globalization API.
- 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)
This object is created and populated by Cordova, and returned to a callback in the case of an error.
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows Phone 8
- Windows 8
- Windows
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');
};
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");
}
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;
}
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 theInAppBrowser
._blank
: Opens in theInAppBrowser
._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
orno
to turn theInAppBrowser
'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 tono
(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 tono
to hide them. Default value isyes
. - hardwareback: set to
yes
to use the hardware back button to navigate backwards through theInAppBrowser
's history. If there is no previous page, theInAppBrowser
will close. The default value isyes
, so you must set it tono
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
orno
(default isno
). 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 tono
(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
orno
to turn the toolbar on or off for the InAppBrowser (defaults toyes
) - enableViewportScale: Set to
yes
orno
to prevent viewport scaling through a meta tag (defaults tono
). - mediaPlaybackRequiresUserAction: Set to
yes
orno
to prevent HTML5 audio or video from autoplaying (defaults tono
). - allowInlineMediaPlayback: Set to
yes
orno
to allow in-line HTML5 media playback, displaying within the browser window rather than a device-specific playback interface. The HTML'svideo
element must also include thewebkit-playsinline
attribute (defaults tono
) - keyboardDisplayRequiresUserAction: Set to
yes
orno
to open the keyboard when form elements receive focus via JavaScript'sfocus()
call (defaults toyes
). - suppressesIncrementalRendering: Set to
yes
orno
to wait until all new view content is received before being rendered (defaults tono
). - presentationstyle: Set to
pagesheet
,formsheet
orfullscreen
to set the presentation style (defaults tofullscreen
). - transitionstyle: Set to
fliphorizontal
,crossdissolve
orcoververtical
to set the transition style (defaults tocoververtical
). - toolbarposition: Set to
top
orbottom
(default isbottom
). 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 tono
(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.
- location: Set to
- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
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');
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
.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;
}
Similar to Firefox OS IAB window visual behaviour can be overridden via inAppBrowserWrap
/inAppBrowserWrapFullscreen
CSS classes
-
Plugin is implemented via iframe,
-
Navigation history (
back
andforward
buttons in LocationBar) is not implemented.
The object returned from a call to cordova.InAppBrowser.open
.
- addEventListener
- removeEventListener
- close
- show
- executeScript
- insertCSS
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.
- loadstart: event fires when the
-
callback: the function that executes when the event fires. The function is passed an
InAppBrowserEvent
object as a parameter.
-
type: the eventname, either
loadstart
,loadstop
,loaderror
, orexit
. (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)
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
loadstart
and loaderror
events are not being fired.
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert(event.url); });
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.
- loadstart: event fires when the
-
callback: the function to execute when the event fires. The function is passed an
InAppBrowserEvent
object.
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
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);
Closes the
InAppBrowser
window.
ref.close();
- ref: reference to the
InAppBrowser
window (InAppBrowser)
- Amazon Fire OS
- Android
- Firefox OS
- iOS
- Windows 8 and 8.1
- Windows Phone 7 and 8
- Browser
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();
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
)
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'hidden=yes');
// some time later...
ref.show();
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
orcode
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 anArray
. For multi-line scripts, this is the return value of the last statement, or the last expression evaluated.
- If the injected script is of type
- Amazon Fire OS
- Android
- iOS
- Windows 8 and 8.1
- Browser
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.executeScript({file: "myscript.js"});
});
- only code key is supported.
Due to MSDN docs the invoked script can return only string values, otherwise the parameter, passed to callback will be [null]
.
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
orcode
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.
- Amazon Fire OS
- Android
- iOS
- Windows
var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstop', function() {
ref.insertCSS({file: "mystyles.css"});
});
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
Use <access>
tags, just as in previous versions of Cordova.
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);
}
cordova plugin add cordova-plugin-media
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Tizen
- Windows 8
- Windows
- Browser
-
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.
var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);
-
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:
var my_media = new Media('cdvfile://localhost/temporary/recording.mp3', ...);
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;
-
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.
-
position: The position within the audio playback, in seconds.
- Not automatically updated during play; call
getCurrentPosition
to update.
- Not automatically updated during play; call
-
duration: The duration of the media, in seconds.
Returns the current position within an audio file. Also updates the Media
object's position
parameter.
media.getCurrentPosition(mediaSuccess, [mediaError]);
-
mediaSuccess: The callback that is passed the current position in seconds.
-
mediaError: (Optional) The callback to execute if an error occurs.
// 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);
Returns the duration of an audio file in seconds. If the duration is unknown, it returns a value of -1.
media.getDuration();
// 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);
Pauses playing an audio file.
media.pause();
// 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);
}
Starts or resumes playing an audio file.
media.play();
// 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();
}
-
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 totrue
(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'sdocuments/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
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();
// Audio player
//
var my_media = new Media(src, onSuccess, onError);
my_media.play();
my_media.stop();
my_media.release();
Sets the current position within an audio file.
media.seekTo(milliseconds);
- milliseconds: The position to set the playback position within the audio, in milliseconds.
// 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);
- Not supported on BlackBerry OS 5 devices.
Set the volume for an audio file.
media.setVolume(volume);
- volume: The volume to set for playback. The value must be within the range of 0.0 to 1.0.
- Android
- iOS
// 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);
}
Starts recording an audio file.
media.startRecord();
- Android
- iOS
- Windows Phone 7 and 8
- Windows
// 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 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 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 theFile
API usingLocalFileSystem.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 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.
-
If a full path is not provided, the recording is placed in the AppData/temp directory. This can be accessed via the
File
API usingLocalFileSystem.TEMPORARY
or 'ms-appdata:///temp/' URI. -
Any subdirectory specified at record time must already exist.
- Not supported on Tizen devices.
Stops playing an audio file.
media.stop();
// 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);
}
Stops recording an audio file.
media.stopRecord();
- Android
- iOS
- Windows Phone 7 and 8
- Windows
// 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);
}
- Not supported on Tizen devices.
A MediaError
object is returned to the mediaError
callback
function when an error occurs.
-
code: One of the predefined error codes listed below.
-
message: An error message describing the details of the error.
MediaError.MEDIA_ERR_ABORTED
= 1MediaError.MEDIA_ERR_NETWORK
= 2MediaError.MEDIA_ERR_DECODE
= 3MediaError.MEDIA_ERR_NONE_SUPPORTED
= 4
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);
}
cordova plugin add cordova-plugin-media-capture
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
- Capture
- CaptureAudioOptions
- CaptureImageOptions
- CaptureVideoOptions
- CaptureCallback
- CaptureErrorCB
- ConfigurationData
- MediaFile
- MediaFileData
- capture.captureAudio
- capture.captureImage
- capture.captureVideo
- MediaFile.getFormatData
-
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[])
Start the audio recorder application and return information about captured audio clip files.
navigator.device.capture.captureAudio(
CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureAudioOptions options]
);
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.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
// 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 does not have a default audio recording application, so a simple user interface is provided.
- Windows Phone 7 does not have a default audio recording application, so a simple user interface is provided.
Encapsulates audio capture configuration options.
-
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.
// 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);
- The
duration
parameter is not supported. Recording lengths cannot be limited programmatically.
- The
duration
parameter is not supported. Recording lengths can't be limited programmatically.
- 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.
- The
limit
parameter is not supported, so only one recording can be created for each invocation.
Start the camera application and return information about captured image files.
navigator.device.capture.captureImage(
CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureImageOptions options]
);
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.
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
Invoking the native camera application while your device is connected via Zune does not work, and the error callback executes.
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.
// 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});
Encapsulates image capture configuration options.
- 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).
// limit capture operation to 3 images
var options = { limit: 3 };
navigator.device.capture.captureImage(captureSuccess, captureError, options);
- The limit parameter is not supported, and only one image is taken per invocation.
Start the video recorder application and return information about captured video clip files.
navigator.device.capture.captureVideo(
CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureVideoOptions options]
);
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.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
// 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});
- 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.
Encapsulates video capture configuration options.
-
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.
// limit capture operation to 3 video clips
var options = { limit: 3 };
navigator.device.capture.captureVideo(captureSuccess, captureError, options);
- The duration property is ignored, so the length of recordings can't be limited programmatically.
- The limit property is ignored. Only one video is recorded per invocation.
- Android supports an additional quality property, to allow capturing video at different qualities. A value of
1
( the default ) means high quality and value of0
means low quality, suitable for MMS messages. See http://developer.android.com/reference/android/provider/MediaStore.html#EXTRA_VIDEO_QUALITY for more details.
// limit capture operation to 1 video clip of low quality
var options = { limit: 1, quality: 0 };
navigator.device.capture.captureVideo(captureSuccess, captureError, options);
Invoked upon a successful media capture operation.
function captureSuccess( MediaFile[] mediaFiles ) { ... };
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.
// 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
}
};
Encapsulates the error code resulting from a failed media capture operation.
- code: One of the pre-defined error codes listed below.
-
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 oflimit
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.
Invoked if an error occurs during a media capture operation.
function captureError( CaptureError error ) { ... };
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
.
// capture error callback
var captureError = function(error) {
navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error');
};
Encapsulates a set of media capture parameters that a device supports.
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. Examples:
video/3gpp
video/quicktime
image/jpeg
audio/amr
audio/wav
-
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)
// 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.
Retrieves format information about the media capture file.
mediaFile.getFormatData(
MediaFileDataSuccessCB successCallback,
[MediaFileDataErrorCB errorCallback]
);
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.
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
The API to access media file format information is limited, so not all
MediaFileData
properties are supported.
Does not provide an API for information about media files, so all
MediaFileData
objects return with default values.
The API to access media file format information is limited, so not all
MediaFileData
properties are supported.
The API to access media file format information is limited, so not all
MediaFileData
properties are supported.
Encapsulates properties of a media capture file.
-
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)
- MediaFile.getFormatData: Retrieves the format information of the media file.
Encapsulates format information about a media file.
-
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)
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.
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
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.
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.
This plugin provides an implementation of an old version of the Network Information API. It provides information about the device's cellular and wifi connection, and whether the device has an internet connection.
cordova plugin add cordova-plugin-network-information
- Amazon Fire OS
- Android
- BlackBerry 10
- Browser
- iOS
- Windows Phone 7 and 8
- Tizen
- Windows
- Firefox OS
The
connection
object, exposed vianavigator.connection
, provides information about the device's cellular and wifi connection.
- connection.type
- Connection.UNKNOWN
- Connection.ETHERNET
- Connection.WIFI
- Connection.CELL_2G
- Connection.CELL_3G
- Connection.CELL_4G
- Connection.CELL
- Connection.NONE
This property offers a fast way to determine the device's network connection state, and type of connection.
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();
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 can't detect the type of cellular network connection.
navigator.connection.type
is set toConnection.CELL
for all cellular data.
-
When running in the emulator, always detects
navigator.connection.type
asConnection.UNKNOWN
. -
Windows Phone can't detect the type of cellular network connection.
navigator.connection.type
is set toConnection.CELL
for all cellular data.
- When running in the Phone 8.1 emulator, always detects
navigator.connection.type
asConnection.ETHERNET
.
- Tizen can only detect a WiFi or cellular connection.
navigator.connection.type
is set toConnection.CELL_2G
for all cellular data.
- Firefox OS can't detect the type of cellular network connection.
navigator.connection.type
is set toConnection.CELL
for all cellular data.
- Browser can't detect the type of network connection.
navigator.connection.type
is always set toConnection.UNKNOWN
when online.
The event fires when an application goes offline, and the device is not connected to the Internet.
document.addEventListener("offline", yourCallbackFunction, false);
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.
document.addEventListener("offline", onOffline, false);
function onOffline() {
// Handle the offline event
}
During initial startup, the first offline event (if applicable) takes at least a second to fire.
When running in the Emulator, the connection.status
is always unknown, so this event does not fire.
The Emulator reports the connection type as Cellular
, which does not change, so the event does not fire.
This event fires when an application goes online, and the device becomes connected to the Internet.
document.addEventListener("online", yourCallbackFunction, false);
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.
document.addEventListener("online", onOnline, false);
function onOnline() {
// Handle the online event
}
During initial startup, the first online
event (if applicable) takes
at least a second to fire, prior to which connection.type
is
UNKNOWN
.
When running in the Emulator, the connection.status
is always unknown, so this event does not fire.
The Emulator reports the connection type as Cellular
, which does not change, so events does not fire.
This plugin displays and hides a splash screen during application launch.
// 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
- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows
- Browser
-
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 theSplashScreenDelay
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" />
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 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.
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>
-
FadeSplashScreen
(boolean, defaults totrue
): Set tofalse
to prevent the splash screen from fading in and out when its display state changes.<preference name="FadeSplashScreen" value="false"/>
-
FadeSplashScreenDuration
(float, defaults to2
): Specifies the number of seconds for the splash screen fade effect to execute.<preference name="FadeSplashScreenDuration" value="4"/>
-
ShowSplashScreenSpinner
(boolean, defaults totrue
): Set tofalse
to hide the splash-screen spinner.<preference name="ShowSplashScreenSpinner" value="false"/>
- splashscreen.show
- splashscreen.hide
Dismiss the splash screen.
navigator.splashscreen.hide();
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);
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
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.
The
StatusBar
object provides some functions to customize the iOS and Android StatusBar.
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
-
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" />
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:
if (cordova.platformId == 'android') {
StatusBar.backgroundColorByHexString("#333");
}
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/>
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
- StatusBar.isVisible
<feature name="StatusBar">
<param name="ios-package" value="CDVStatusBar" onload="true" />
</feature>
On iOS 7, make the statusbar overlay or not overlay the WebView.
StatusBar.overlaysWebView(true);
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.
- iOS
StatusBar.overlaysWebView(true);
StatusBar.overlaysWebView(false);
Use the default statusbar (dark text, for light backgrounds).
StatusBar.styleDefault();
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
Use the lightContent statusbar (light text, for dark backgrounds).
StatusBar.styleLightContent();
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
Use the blackTranslucent statusbar (light text, for dark backgrounds).
StatusBar.styleBlackTranslucent();
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
Use the blackOpaque statusbar (light text, for dark backgrounds).
StatusBar.styleBlackOpaque();
- iOS
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
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
- iOS
- Android 5+
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
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
- iOS
- Android 5+
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
Hide the statusbar.
StatusBar.hide();
- iOS
- Android
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
Shows the statusbar.
StatusBar.show();
- iOS
- Android
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
Read this property to see if the statusbar is visible or not.
if (StatusBar.isVisible) {
// do something
}
- iOS
- Android
- Windows Phone 7
- Windows Phone 8
- Windows Phone 8.1
The cordova-plugin-test-framework
plugin does two things:
- Defines the interface for cordova plugins to write tests
- Provides a test harness for actually running those tests
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.
-
Use your existing cordova app, or create a new one.
-
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
-
Follow the docs for Setting up the test harness.
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
.
The cordova-plugin-test-framework
plugin will automatically find all tests
modules across all plugins for which the nested tests plugin is installed.
Simply export a function named defineAutoTests
, which (gasp!) defines your auto-tests when run. Use the jasmine-2.0
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.
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.
### ExampleSee: cordova-plugin-device
tests.
-
Use your existing cordova app, or create a new one.
-
Add this plugin:
cordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-test-framework.git
-
Change the start page in
config.xml
with<content src="cdvtests/index.html" />
or navigate tocdvtests/index.html
from within your app. -
Thats it!
-
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.
- A: Not likely. If you want, you can. Then your app could even embed a link to the test page (
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);
}
cordova plugin add cordova-plugin-vibration
navigator.vibrate,
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
navigator.notification.cancelVibration
- Android
- Windows Phone 8
- Windows (Windows Phone 8.1 devices only)
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.
Vibrates the device for a given amount of time.
navigator.notification.vibrate(time)
- time: Milliseconds to vibrate the device. (Number)
// Vibrate for 2.5 seconds
navigator.notification.vibrate(2500);
-
time: Ignores the specified time and vibrates for a pre-set amount of time.
navigator.notification.vibrate(); navigator.notification.vibrate(2500); // 2500 is ignored
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)
// 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]);
Immediately cancels any currently running vibration.
navigator.notification.cancelVibration()
*Note - due to alignment with w3c spec, the starred methods will be phased out
This plugin implements a whitelist policy for navigating the application webview on Cordova 4.0
- Android 4.0.0 or above
- iOS 4.0.0 or above
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:*" />
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="*" />
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.
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 <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">
This branch stores plugins that are built by the Cordova team, but are not supported as "core" plugins.