untitled 1

Download Untitled 1

If you can't read please download the document

Upload: icelon

Post on 01-Dec-2014

136 views

Category:

Documents


0 download

TRANSCRIPT

PhoneGap Documentation Accelerometer Captures device motion in the x, y, and z direction.

Methods accelerometer.getCurrentAcceleration accelerometer.watchAcceleration accelerometer.clearWatch

Arguments accelerometerSuccess accelerometerError accelerometerOptions

Objects (Read-Only) Acceleration

accelerometer.getCurrentAcceleration Get the current acceleration along the x, y, and z axis. navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);

Description The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current device orientation. The accelerometer can detect 3D movement along the x, y, and z axis. The acceleration is returned using the accelerometerSuccess callback function. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); }; function onError() { alert('onError!');

}; navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);

Full Example Acceleration Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } Example getCurrentAcceleration

iPhone Quirks iPhone doesn't have 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 will give you the last value reported from a phoneGap watchAccelerometer call.

accelerometer.watchAcceleration At a regular interval, get the acceleration along the x, y, and z axis. var watchID = navigator.accelerometer.watchAcceleration(accelerometerSuccess, accelerometerError, [accelerometerOptions]);

Description The accelerometer is a motion sensor that detects the change (delta) in movement relative to the current position. The accelerometer can detect 3D movement along the x, y, and z axis. The accelerometer.watchAcceleration gets the device's current acceleration at a regular interval. Each time the Acceleration is retrieved, the accelerometerSuccess callback function is executed. Specify the interval in milliseconds via the frequency parameter in the acceleratorOptions object. The returned watch ID references references the accelerometer watch interval. The watch ID can be used with accelerometer.clearWatch to stop watching the accelerometer. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); }; function onError() { alert('onError!'); }; var options = { frequency: 3000 }; // Update every 3 seconds var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);

Full Example Acceleration Example // The watch id references the current `watchAcceleration` var watchID = null; // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { startWatch(); } // Start watching the acceleration // function startWatch() { // Update acceleration every 3 seconds var options = { frequency: 3000 }; watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); } // Stop watching the acceleration // function stopWatch() { if (watchID) {

navigator.accelerometer.clearWatch(watchID); watchID = null; } } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { var element = document.getElementById('accelerometer'); element.innerHTML = 'Acceleration X: ' + acceleration.x + '
' + 'Acceleration Y: ' + acceleration.y + '
' + 'Acceleration Z: ' + acceleration.z + '
' + 'Timestamp: ' + acceleration.timestamp + '
'; } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } Waiting for accelerometer...

iPhone Quirks At the interval requested, PhoneGap will call the success callback function and pass the accelerometer results. However, in requests to the device PhoneGap restricts the interval to minimum of every 40ms and a maximum of every 1000ms. For example, if you request an interval of 3 seconds (3000ms), PhoneGap will request an interval of 1 second from the device but invoke the success callback at the requested interval of 3 seconds.

accelerometer.clearWatch Stop watching the Acceleration referenced by the watch ID parameter. navigator.accelerometer.clearWatch(watchID);

watchID: The ID returned by accelerometer.watchAcceleration.

Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); // ... later on ... navigator.accelerometer.clearWatch(watchID);

Full Example

Acceleration Example // The watch id references the current `watchAcceleration` var watchID = null; // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { startWatch(); } // Start watching the acceleration // function startWatch() { // Update acceleration every 3 seconds var options = { frequency: 3000 }; watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); } // Stop watching the acceleration // function stopWatch() { if (watchID) { navigator.accelerometer.clearWatch(watchID); watchID = null; } } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { var element = document.getElementById('accelerometer'); element.innerHTML = 'Acceleration X: ' + acceleration.x + '
' + 'Acceleration Y: ' + acceleration.y + '
' + 'Acceleration Z: ' + acceleration.z + '
' + 'Timestamp: ' + acceleration.timestamp + '
'; } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } Waiting for accelerometer... Stop Watching

Acceleration Contains Accelerometer data captured at a specific point in time. Properties

x: Amount of motion on the x-axis. Range [0, 1] (Number) y: Amount of motion on the y-axis. Range [0, 1] (Number) z: Amount of motion on the z-axis. Range [0, 1] (Number) timestamp: Creation timestamp in milliseconds. (DOMTimeStamp)

Description This object is created and populated by PhoneGap, and returned by an Accelerometer method. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); }; function onError() { alert('onError!'); }; navigator.accelerometer.getCurrentAcceleration(onSuccess, onError);

Full Example Acceleration Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); } // onSuccess: Get a snapshot of the current acceleration // function onSuccess() { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' +

'Timestamp: ' + acceleration.timestamp + '\n'); } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } Example getCurrentAcceleration

accelerometerSuccess onSuccess callback function that provides the Acceleration information. function(acceleration) { // Do something }

Parameters

acceleration: The acceleration at a single moment in time. (Acceleration)

Example function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); };

accelerometerError onError callback function for acceleration functions. function() { // Handle the error }

accelerometerOptions An optional parameter to customize the retrieval of the accelerometer. Options

frequency: How often to retrieve the Acceleration in milliseconds. (Number) (Default: 10000)

Camera The camera object provides access to the device's default camera application.

Methods camera.getPicture

camera.getPicture Takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded String or as the URI of an image file. navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] );

Description Function camera.getPicture opens the device's default camera application so that the user can take a picture (if Camera.sourceType = Camera.PictureSourceType.CAMERA, which is the default). Once the photo is taken, the camera application closes and your application is restored. If Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected. The return value will be sent to the cameraSuccess function, in one of the following formats, depending on the cameraOptions you specify:

A String containing the Base64 encoded photo image (default). A String representing the image file location on local storage.

You can do whatever you want with the encoded image or URI, for example:

Render the image in an tag (see example below)

Save the data locally (LocalStorage, Lawnchair, etc) Post the data to a remote server

Note: The image quality of pictures taken using the camera on newer devices is quite good. Encoding such images using Base64 has caused memory issues on some of these devices (iPhone 4, BlackBerry Torch 9800). Therefore, using FILE_URI as the 'Camera.destinationType' is highly recommended. Supported Platforms Android Blackberry WebWorks (OS 5.0 and higher) iPhone

Quick Example Take photo and retrieve Base64-encoded image: navigator.camera.getPicture(onSuccess, onFail, { quality: 50 }); function onSuccess(imageData) { var image = document.getElementById('myImage'); image.src = "data:image/jpeg;base64," + imageData; } function onFail(message) { alert('Failed because: ' + message); }

Take photo and retrieve image 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); }

Full Example Capture Photo var pictureSource; // picture source var destinationType; // sets the format of returned value // Wait for PhoneGap to connect with the device // document.addEventListener("deviceready",onDeviceReady,false); // PhoneGap is ready to be used! // function onDeviceReady() { pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType; } // Called when a photo is successfully retrieved //

function onPhotoDataSuccess(imageData) { // Uncomment to view the base64 encoded image data // console.log(imageData); // Get image handle // var smallImage = document.getElementById('smallImage'); // Unhide image elements // smallImage.style.display = 'block'; // Show the captured photo // The inline CSS rules are used to resize the image // smallImage.src = "data:image/jpeg;base64," + imageData; } // Called when a photo is successfully retrieved // function onPhotoURISuccess(imageURI) { // Uncomment to view the image file URI // console.log(imageURI); // Get image handle // var largeImage = document.getElementById('largeImage'); // Unhide image elements // largeImage.style.display = 'block'; // Show the captured photo // The inline CSS rules are used to resize the image // largeImage.src = imageURI; } // A button will call this function // function capturePhoto() { // Take picture using device camera and retrieve image as base64-encoded string navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 }); } // A button will call this function // function capturePhotoEdit() { // Take picture using device camera, allow edit, and retrieve image as base64-encoded string navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true }); } // A button will call this function // function getPhoto(source) { // Retrieve image file location from specified source navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, destinationType: destinationType.FILE_URI, sourceType: source }); } // Called if something bad happens. // function onFail(message) { alert('Failed because: ' + message); } Capture Photo
Capture Editable Photo
From Photo Library
From Photo Album

cameraSuccess onSuccess callback function that provides the image data. function(imageData) { // Do something with the image }

Parameters

imageData: Base64 encoding of the image data, OR the image file URI, depending on cameraOptions used. (String)

Example // Show image // function cameraCallback(imageData) { var image = document.getElementById('myImage'); image.src = "data:image/jpeg;base64," + imageData; }

cameraError onError callback function that provides an error message. function(message) { // Show a helpful message }

Parameters

message: The message is provided by the device's native code. (String)

cameraOptions Optional parameters to customize the camera settings. { quality : 75, destinationType : Camera.DestinationType.DATA_URL, sourceType : Camera.PictureSourceType.CAMERA, allowEdit : true, encodingType: Camera.EncodingType.JPEG, targetWidth: 100, targetHeight: 100 };

Options

quality: Quality of saved image. Range is [0, 100]. (Number)

destinationType: Choose the format of the return value. Defined in navigator.camera.DestinationType (Number) Camera.DestinationType = { DATA_URL : 0, // Return image as base64 encoded string FILE_URI : 1 // Return image file URI };

sourceType: Set the source of the picture. Defined in nagivator.camera.PictureSourceType (Number) Camera.PictureSourceType = { PHOTOLIBRARY : 0, CAMERA : 1, SAVEDPHOTOALBUM : 2 };

allowEdit: Allow simple editing of image before selection. (Boolean) EncodingType: Choose the encoding of the returned image file. 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 is maintained. (Number) targetHeight: Height in pixels to scale image. Must be used with targetWidth. Aspect ratio is maintained. (Number)

Android Quirks

Ignores the allowEdit parameter. Camera.PictureSourceType.PHOTOLIBRARY and Camera.PictureSourceType.SAVEDPHOTOALBUM both display the same photo album. Camera.EncodingType is not supported.

BlackBerry Quirks

Ignores the quality parameter. Ignores the sourceType parameter. Ignores the allowEdit parameter. Application must have key injection permissions to close native Camera application after photo is taken. Using Large image sizes may result in inability to encode image on later model devices with high resolution cameras (e.g. Torch 9800).

Palm Quirks

Ignores the quality parameter. Ignores the sourceType parameter. Ignores the allowEdit parameter.

iPhone Quirks

Set quality below 50 to avoid memory error on some devices. When destinationType.FILE_URI is used, photos are saved in the application's temporary directory. The contents of the application's temporary directory is deleted when the application ends. Developers may also delete the contents of this directory using the navigator.fileMgr APIs if storage space is a concern.

Capture Provides access to the audio, image, and video capture capabilities of the device.

Objects Capture CaptureAudioOptions CaptureImageOptions CaptureVideoOptions CaptureCB CaptureErrorCB ConfigurationData MediaFile MediaFileData

Methods Scope The capture object is assigned to the navigator.device object, and therefore has global scope. // The global capture object var capture = navigator.device.capture; capture.captureAudio capture.captureImage capture.captureVideo MediaFile.getFormatData

Properties

supportedAudioModes: The audio recording formats supported by the device. (ConfigurationData[])

supportedImageModes: The recording image sizes and formats supported by the device. (ConfigurationData[]) supportedVideoModes: The recording video resolutions and formats supported by the device. (ConfigurationData[])

Methods capture.captureAudio: Launch the device audio recording application for recording audio clip(s). capture.captureImage: Launch the device camera application for taking image(s). capture.captureVideo: Launch the device video recorder application for recording video(s).

Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

capture.captureAudio Start the audio recorder application and return information about captured audio clip file(s). navigator.device.capture.captureAudio( CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureAudioOptions options] );

Description This method 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 the limit parameter in CaptureAudioOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user records a single audio clip. When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured audio clip file. If the operation is terminated by the user before an audio clip is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // capture callback

var captureSuccess = function(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start audio capture navigator.device.capture.captureAudio(captureSuccess, captureError, {limit:2});

Full Example Capture Audio // Called when capture operation is finished // function captureSuccess(mediaFiles) { var i, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { uploadFile(mediaFiles[i]); } } // Called if something bad happens. // function captureError(error) { var msg = 'An error occurred during capture: ' + error.code; navigator.notification.alert(msg, null, 'Uh oh!'); } // A button will call this function // function captureAudio() { // Launch device audio recording application, // allowing user to capture up to 2 audio clips navigator.device.capture.captureAudio(captureSuccess, captureError, {limit: 2}); } // Upload files to server function uploadFile(mediaFile) { var ft = new FileTransfer(), path = mediaFile.fullPath, name = mediaFile.name; ft.upload(path, "http://my.domain.com/upload.php", function(result) { console.log('Upload success: ' + result.responseCode); console.log(result.bytesSent + ' bytes sent'); }, function(error) { console.log('Error uploading file ' + path + ': ' + error.code); }, { fileName: name }); } Capture Audio

BlackBerry WebWorks Quirks

PhoneGap for BlackBerry WebWorks attempts to launch the Voice Notes Recorder application, provided by RIM, to capture the audio recordings. The developer will receive a CaptureError.CAPTURE_NOT_SUPPORTED error code if the application is not installed on the device.

iOS Quirks iOS does not have a default audio recording application so a simple user interface is provided.

CaptureAudioOptions Encapsulates audio capture configuration options.

Properties

limit: The maximum number of audio clips the device user can record in a single capture operation. The value must be greater than or equal to 1 (defaults to 1). duration: The maximum duration of an audio sound clip, in seconds. mode: The selected audio mode. The value must match one of the elements in capture.supportedAudioModes.

Quick Example // limit capture operation to 3 media files, no longer than 10 seconds each var options = { limit: 3, duration: 10 }; navigator.device.capture.captureAudio(captureSuccess, captureError, options);

Android Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Adaptive Multi-Rate (AMR) format (audio/amr).

BlackBerry WebWorks Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Adaptive Multi-Rate (AMR) format (audio/amr).

iOS Quirks

The limit parameter is not supported. One recording can be created for each invocation. The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Waveform Audio (WAV) format (audio/wav).

capture.captureImage Start the camera application and return information about captured image file(s). navigator.device.capture.captureImage( CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureImageOptions options] );

Description This method starts an asynchronous operation to capture images using the device camera application. The operation allows the device user to capture multiple images in a single session. The capture operation ends when either the user exits the camera application, or the maximum number of images, specified by the limit parameter in CaptureImageOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user captures a single image. When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured image file. If the operation is terminated by the user before an image is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // capture callback var captureSuccess = function(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start image capture navigator.device.capture.captureImage(captureSuccess, captureError, {limit:2});

Full Example Capture Image

// Called when capture operation is finished // function captureSuccess(mediaFiles) { var i, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { uploadFile(mediaFiles[i]); } } // Called if something bad happens. // function captureError(error) { var msg = 'An error occurred during capture: ' + error.code; navigator.notification.alert(msg, null, 'Uh oh!'); } // A button will call this function // function captureImage() { // Launch device camera application, // allowing user to capture up to 2 images navigator.device.capture.captureImage(captureSuccess, captureError, {limit: 2}); } // Upload files to server function uploadFile(mediaFile) { var ft = new FileTransfer(), path = mediaFile.fullPath, name = mediaFile.name; ft.upload(path, "http://my.domain.com/upload.php", function(result) { console.log('Upload success: ' + result.responseCode); console.log(result.bytesSent + ' bytes sent'); }, function(error) { console.log('Error uploading file ' + path + ': ' + error.code); }, { fileName: name }); } Capture Image

CaptureImageOptions Encapsulates image capture configuration options.

Properties

limit: The maximum number of images the device user can capture in a single capture operation. The value must be greater than or equal to 1 (defaults to 1). mode: The selected image mode. The value must match one of the elements in capture.supportedImageModes.

Quick Example // limit capture operation to 3 images

var options = { limit: 3 }; navigator.device.capture.captureImage(captureSuccess, captureError, options);

Android Quirks

The mode parameter is not supported. The image size and format cannot be altered programmatically; however, the image size can be altered by the device user. Images are saved in JPEG format (image/jpeg).

BlackBerry WebWorks Quirks

The mode parameter is not supported. The image size and format cannot be altered programmatically; however, the image size can be altered by the device user. Images are saved in JPEG format (image/jpeg).

iOS Quirks

The limit parameter is not supported. One image is taken per invocation. The mode parameter is not supported. The image size and format cannot be altered programmatically. Images are saved in JPEG format (image/jpeg).

capture.captureVideo Start the video recorder application and return information about captured video clip file(s). navigator.device.capture.captureVideo( CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureVideoOptions options] );

Description This method starts an asynchronous operation to capture video recordings using the device video 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 video recording application, or the maximum number of recordings, specified by the limit parameter in CaptureVideoOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user records a single video clip. When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured video clip file. If the operation is terminated by the user before an video clip is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // capture callback var captureSuccess = function(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start video capture navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:2});

Full Example Capture Video // Called when capture operation is finished // function captureSuccess(mediaFiles) { var i, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { uploadFile(mediaFiles[i]); } } // Called if something bad happens. // function captureError(error) { var msg = 'An error occurred during capture: ' + error.code; navigator.notification.alert(msg, null, 'Uh oh!'); } // A button will call this function // function captureVideo() { // Launch device video recording application, // allowing user to capture up to 2 video clips navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 2}); } // Upload files to server function uploadFile(mediaFile) { var ft = new FileTransfer(), path = mediaFile.fullPath, name = mediaFile.name; ft.upload(path, "http://my.domain.com/upload.php", function(result) { console.log('Upload success: ' + result.responseCode); console.log(result.bytesSent + ' bytes sent'); }, function(error) { console.log('Error uploading file ' + path + ': ' + error.code); }, { fileName: name }); } Capture Video

BlackBerry WebWorks Quirks

PhoneGap for BlackBerry WebWorks attempts to launch the Video Recorder application, provided by RIM, to capture the video recordings. The developer will receive a CaptureError.CAPTURE_NOT_SUPPORTED error code if the application is not installed on the device.

CaptureVideoOptions Encapsulates video capture configuration options.

Properties

limit: The maximum number of video clips the device 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. mode: The selected video capture mode. The value must match one of the elements in capture.supportedVideoModes.

Quick Example // limit capture operation to 3 video clips var options = { limit: 3 }; navigator.device.capture.captureVideo(captureSuccess, captureError, options);

Android Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The video size and format cannot be altered programmatically; however, these parameters can be changed by the device user. By default, videos are recorded in 3GPP (video/3gpp) format.

BlackBerry WebWorks Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The video size and format cannot be altered programmatically; however, these parameters can be changed by the device user. By default, videos are recorded in 3GPP (video/3gpp) format.

iOS Quirks

The limit parameter is not supported. One video is recorded per invocation.

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The video size and format cannot be altered programmatically. By default, videos are recorded in MOV (video/quicktime) format.

CaptureCB Invoked upon a successful media capture operation. function captureSuccess( MediaFile[] mediaFiles ) { ... };

Description This function is invoked after a successful capture operation has completed. This means 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. Quick Example // capture callback function captureSuccess(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } };

CaptureErrorCB Invoked if an error occurs during a media capture operation. function captureError( CaptureError error ) { ... };

Description This function is invoked if an error occurs when trying to launch a media capture operation and the capture application is busy, if an error occurs while the capture operation is taking place, or if the capture operation has been canceled by the user before any media files have been captured. This function is invoked with a CaptureError object containing an appropriate error code. Quick Example // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); };

ConfigurationData Encapsulates a set of media capture parameters that a device supports.

Description This object is used to describe 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

Properties

type: The ASCII-encoded string in lower case representing the media type. (DOMString) height: The height of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number) width: The width of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number)

Quick Example // retrieve supported image modes var imageModes = navigator.device.capture.supportedImageModes; // Select mode that has the highest horizontal resolution var width = 0; var selectedmode; for each (var mode in imageModes) { if (mode.width > width) { width = mode.width; selectedmode = mode; } } Not supported by any platform. All configuration data arrays are empty.

MediaFile Encapsulates properties of a media capture file.

Properties

name: The name of the file, without path information. (DOMString) fullPath: The full path of the file, including the name. (DOMString)

type: The mime type (DOMString) lastModifiedDate: The date and time that the file was last modified. (Date) size: The size of the file, in bytes. (Number)

Methods

MediaFile.getFormatData: Retrieves the format information of the media file.

MediaFile.getFormatData Retrieves format information about the media capture file. mediaFile.getFormatData( MediaFileDataSuccessCB successCallback, [MediaFileDataErrorCB errorCallback] );

Description This function asynchronously attempts to retrieve the format information for the media file. If successful, it invokes the MediaFileDataSuccessCB callback with a MediaFileData object. If the attempt fails, this function will invoke the MediaFileDataErrorCB callback. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

BlackBerry WebWorks Quirks There is no API that provides format information of media files. Therefore, all MediaFileData objects will be returned with default values. See MediaFileData documentation. Android Quirks The API for retrieving media file format information is limited. Therefore, not all MediaFileData properties are supported. See MediaFileData documentation. iOS Quirks The API for retrieving media file format information is limited. Therefore, not all MediaFileData properties are supported. See MediaFileData documentation.

MediaFileData Encapsulates format information about a media file.

Properties

codecs: The actual format of the audio and video content. (DOMString) bitrate: The average bitrate of the content. In case of an image, this attribute has value 0. (Number) height: The height of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number) width: The width of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number) duration: The length of the video or sound clip in seconds. In the case of an image, this attribute has value 0. (Number)

BlackBerry WebWorks Quirks There is no API that provides format information of media files. So the MediaFileData object returned by the MediaFile.getFormatData function will have the following default values:

codecs: Not supported. The attribute will always be null. bitrate: Not supported. The attribute will always be 0. height: Not supported. The attribute will always be 0. width: Not supported. The attribute will always be 0. duration: Not supported. The attribute will always be 0.

Android Quirks Support for the MediaFileData properties is as follows:

codecs: Not supported. The attribute will always be null. bitrate: Not supported. The attribute will always be 0. height: Supported. (Image and video files only). width: Supported. (Image and video files only). duration: Supported. (Audio and video files only).

iOS Quirks Support for the MediaFileData properties is as follows:

Capture

codecs: Not supported. The attribute will always be null. bitrate: Supported on iOS4 devices for audio only. The attribute will always be 0 for image and video. height: Supported. (Image and video files only). width: Supported. (Image and video files only). duration: Supported. (Audio and video files only).

Provides access to the audio, image, and video capture capabilities of the device.

Objects Capture CaptureAudioOptions CaptureImageOptions CaptureVideoOptions CaptureCB CaptureErrorCB ConfigurationData MediaFile MediaFileData

Methods Scope The capture object is assigned to the navigator.device object, and therefore has global scope. // The global capture object var capture = navigator.device.capture; capture.captureAudio capture.captureImage capture.captureVideo MediaFile.getFormatData

Properties

supportedAudioModes: The audio recording formats supported by the device. (ConfigurationData[]) supportedImageModes: The recording image sizes and formats supported by the device. (ConfigurationData[]) supportedVideoModes: The recording video resolutions and formats supported by the device. (ConfigurationData[])

Methods capture.captureAudio: Launch the device audio recording application for recording audio clip(s). capture.captureImage: Launch the device camera application for taking image(s). capture.captureVideo: Launch the device video recorder application for recording video(s).

Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

capture.captureAudio Start the audio recorder application and return information about captured audio clip file(s). navigator.device.capture.captureAudio( CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureAudioOptions options] );

Description This method 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 the limit parameter in CaptureAudioOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user records a single audio clip. When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured audio clip file. If the operation is terminated by the user before an audio clip is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // capture callback var captureSuccess = function(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback

var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start audio capture navigator.device.capture.captureAudio(captureSuccess, captureError, {limit:2});

Full Example Capture Audio // Called when capture operation is finished // function captureSuccess(mediaFiles) { var i, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { uploadFile(mediaFiles[i]); } } // Called if something bad happens. // function captureError(error) { var msg = 'An error occurred during capture: ' + error.code; navigator.notification.alert(msg, null, 'Uh oh!'); } // A button will call this function // function captureAudio() { // Launch device audio recording application, // allowing user to capture up to 2 audio clips navigator.device.capture.captureAudio(captureSuccess, captureError, {limit: 2}); } // Upload files to server function uploadFile(mediaFile) { var ft = new FileTransfer(), path = mediaFile.fullPath, name = mediaFile.name; ft.upload(path, "http://my.domain.com/upload.php", function(result) { console.log('Upload success: ' + result.responseCode); console.log(result.bytesSent + ' bytes sent'); }, function(error) { console.log('Error uploading file ' + path + ': ' + error.code); }, { fileName: name }); } Capture Audio

BlackBerry WebWorks Quirks

PhoneGap for BlackBerry WebWorks attempts to launch the Voice Notes Recorder application, provided by RIM, to capture the audio recordings. The developer will receive a CaptureError.CAPTURE_NOT_SUPPORTED error code if the application is not installed on the device.

iOS Quirks iOS does not have a default audio recording application so a simple user interface is provided.

CaptureAudioOptions Encapsulates audio capture configuration options.

Properties

limit: The maximum number of audio clips the device user can record in a single capture operation. The value must be greater than or equal to 1 (defaults to 1). duration: The maximum duration of an audio sound clip, in seconds. mode: The selected audio mode. The value must match one of the elements in capture.supportedAudioModes.

Quick Example // limit capture operation to 3 media files, no longer than 10 seconds each var options = { limit: 3, duration: 10 }; navigator.device.capture.captureAudio(captureSuccess, captureError, options);

Android Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Adaptive Multi-Rate (AMR) format (audio/amr).

BlackBerry WebWorks Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Adaptive Multi-Rate (AMR) format (audio/amr).

iOS Quirks

The limit parameter is not supported. One recording can be created for each invocation. The mode parameter is not supported. The audio recording format cannot be altered programmatically. Recordings are encoded using Waveform Audio (WAV) format (audio/wav).

capture.captureImage Start the camera application and return information about captured image file(s). navigator.device.capture.captureImage( CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureImageOptions options] );

Description This method starts an asynchronous operation to capture images using the device camera application. The operation allows the device user to capture multiple images in a single session. The capture operation ends when either the user exits the camera application, or the maximum number of images, specified by the limit parameter in CaptureImageOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user captures a single image. When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured image file. If the operation is terminated by the user before an image is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // capture callback var captureSuccess = function(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start image capture navigator.device.capture.captureImage(captureSuccess, captureError, {limit:2});

Full Example Capture Image

// Called when capture operation is finished // function captureSuccess(mediaFiles) { var i, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { uploadFile(mediaFiles[i]); } } // Called if something bad happens. // function captureError(error) { var msg = 'An error occurred during capture: ' + error.code; navigator.notification.alert(msg, null, 'Uh oh!'); } // A button will call this function // function captureImage() { // Launch device camera application, // allowing user to capture up to 2 images navigator.device.capture.captureImage(captureSuccess, captureError, {limit: 2}); } // Upload files to server function uploadFile(mediaFile) { var ft = new FileTransfer(), path = mediaFile.fullPath, name = mediaFile.name; ft.upload(path, "http://my.domain.com/upload.php", function(result) { console.log('Upload success: ' + result.responseCode); console.log(result.bytesSent + ' bytes sent'); }, function(error) { console.log('Error uploading file ' + path + ': ' + error.code); }, { fileName: name }); } Capture Image

CaptureImageOptions Encapsulates image capture configuration options.

Properties

limit: The maximum number of images the device user can capture in a single capture operation. The value must be greater than or equal to 1 (defaults to 1). mode: The selected image mode. The value must match one of the elements in capture.supportedImageModes.

Quick Example // limit capture operation to 3 images

var options = { limit: 3 }; navigator.device.capture.captureImage(captureSuccess, captureError, options);

Android Quirks

The mode parameter is not supported. The image size and format cannot be altered programmatically; however, the image size can be altered by the device user. Images are saved in JPEG format (image/jpeg).

BlackBerry WebWorks Quirks

The mode parameter is not supported. The image size and format cannot be altered programmatically; however, the image size can be altered by the device user. Images are saved in JPEG format (image/jpeg).

iOS Quirks

The limit parameter is not supported. One image is taken per invocation. The mode parameter is not supported. The image size and format cannot be altered programmatically. Images are saved in JPEG format (image/jpeg).

capture.captureVideo Start the video recorder application and return information about captured video clip file(s). navigator.device.capture.captureVideo( CaptureCB captureSuccess, CaptureErrorCB captureError, [CaptureVideoOptions options] );

Description This method starts an asynchronous operation to capture video recordings using the device video 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 video recording application, or the maximum number of recordings, specified by the limit parameter in CaptureVideoOptions, has been reached. If no value is provided for the limit parameter, a default value of one (1) is used, and the capture operation will terminate after the user records a single video clip. When the capture operation is finished, it will invoke the CaptureCB callback with an array of MediaFile objects describing each captured video clip file. If the operation is terminated by the user before an video clip is captured, the CaptureErrorCB callback will be invoked with a CaptureError object with the CaptureError.CAPTURE_NO_MEDIA_FILES error code. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // capture callback var captureSuccess = function(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } }; // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); }; // start video capture navigator.device.capture.captureVideo(captureSuccess, captureError, {limit:2});

Full Example Capture Video // Called when capture operation is finished // function captureSuccess(mediaFiles) { var i, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { uploadFile(mediaFiles[i]); } } // Called if something bad happens. // function captureError(error) { var msg = 'An error occurred during capture: ' + error.code; navigator.notification.alert(msg, null, 'Uh oh!'); } // A button will call this function // function captureVideo() { // Launch device video recording application, // allowing user to capture up to 2 video clips navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 2}); } // Upload files to server function uploadFile(mediaFile) { var ft = new FileTransfer(), path = mediaFile.fullPath, name = mediaFile.name; ft.upload(path, "http://my.domain.com/upload.php", function(result) { console.log('Upload success: ' + result.responseCode); console.log(result.bytesSent + ' bytes sent'); }, function(error) { console.log('Error uploading file ' + path + ': ' + error.code); }, { fileName: name }); } Capture Video

BlackBerry WebWorks Quirks

PhoneGap for BlackBerry WebWorks attempts to launch the Video Recorder application, provided by RIM, to capture the video recordings. The developer will receive a CaptureError.CAPTURE_NOT_SUPPORTED error code if the application is not installed on the device.

CaptureVideoOptions Encapsulates video capture configuration options.

Properties

limit: The maximum number of video clips the device 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. mode: The selected video capture mode. The value must match one of the elements in capture.supportedVideoModes.

Quick Example // limit capture operation to 3 video clips var options = { limit: 3 }; navigator.device.capture.captureVideo(captureSuccess, captureError, options);

Android Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The video size and format cannot be altered programmatically; however, these parameters can be changed by the device user. By default, videos are recorded in 3GPP (video/3gpp) format.

BlackBerry WebWorks Quirks

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The video size and format cannot be altered programmatically; however, these parameters can be changed by the device user. By default, videos are recorded in 3GPP (video/3gpp) format.

iOS Quirks

The limit parameter is not supported. One video is recorded per invocation.

The duration parameter is not supported. Recording lengths cannot be limited programmatically. The mode parameter is not supported. The video size and format cannot be altered programmatically. By default, videos are recorded in MOV (video/quicktime) format.

CaptureCB Invoked upon a successful media capture operation. function captureSuccess( MediaFile[] mediaFiles ) { ... };

Description This function is invoked after a successful capture operation has completed. This means 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. Quick Example // capture callback function captureSuccess(mediaFiles) { var i, path, len; for (i = 0, len = mediaFiles.length; i < len; i += 1) { path = mediaFiles[i].fullPath; // do something interesting with the file } };

CaptureErrorCB Invoked if an error occurs during a media capture operation. function captureError( CaptureError error ) { ... };

Description This function is invoked if an error occurs when trying to launch a media capture operation and the capture application is busy, if an error occurs while the capture operation is taking place, or if the capture operation has been canceled by the user before any media files have been captured. This function is invoked with a CaptureError object containing an appropriate error code. Quick Example // capture error callback var captureError = function(error) { navigator.notification.alert('Error code: ' + error.code, null, 'Capture Error'); };

ConfigurationData Encapsulates a set of media capture parameters that a device supports.

Description This object is used to describe 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

Properties

type: The ASCII-encoded string in lower case representing the media type. (DOMString) height: The height of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number) width: The width of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number)

Quick Example // retrieve supported image modes var imageModes = navigator.device.capture.supportedImageModes; // Select mode that has the highest horizontal resolution var width = 0; var selectedmode; for each (var mode in imageModes) { if (mode.width > width) { width = mode.width; selectedmode = mode; } } Not supported by any platform. All configuration data arrays are empty.

MediaFile Encapsulates properties of a media capture file.

Properties

name: The name of the file, without path information. (DOMString) fullPath: The full path of the file, including the name. (DOMString)

type: The mime type (DOMString) lastModifiedDate: The date and time that the file was last modified. (Date) size: The size of the file, in bytes. (Number)

Methods

MediaFile.getFormatData: Retrieves the format information of the media file.

MediaFile.getFormatData Retrieves format information about the media capture file. mediaFile.getFormatData( MediaFileDataSuccessCB successCallback, [MediaFileDataErrorCB errorCallback] );

Description This function asynchronously attempts to retrieve the format information for the media file. If successful, it invokes the MediaFileDataSuccessCB callback with a MediaFileData object. If the attempt fails, this function will invoke the MediaFileDataErrorCB callback. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

BlackBerry WebWorks Quirks There is no API that provides format information of media files. Therefore, all MediaFileData objects will be returned with default values. See MediaFileData documentation. Android Quirks The API for retrieving media file format information is limited. Therefore, not all MediaFileData properties are supported. See MediaFileData documentation. iOS Quirks The API for retrieving media file format information is limited. Therefore, not all MediaFileData properties are supported. See MediaFileData documentation.

MediaFileData Encapsulates format information about a media file.

Properties

codecs: The actual format of the audio and video content. (DOMString) bitrate: The average bitrate of the content. In case of an image, this attribute has value 0. (Number) height: The height of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number) width: The width of the image or video in pixels. In the case of a sound clip, this attribute has value 0. (Number) duration: The length of the video or sound clip in seconds. In the case of an image, this attribute has value 0. (Number)

BlackBerry WebWorks Quirks There is no API that provides format information of media files. So the MediaFileData object returned by the MediaFile.getFormatData function will have the following default values:

codecs: Not supported. The attribute will always be null. bitrate: Not supported. The attribute will always be 0. height: Not supported. The attribute will always be 0. width: Not supported. The attribute will always be 0. duration: Not supported. The attribute will always be 0.

Android Quirks Support for the MediaFileData properties is as follows:

codecs: Not supported. The attribute will always be null. bitrate: Not supported. The attribute will always be 0. height: Supported. (Image and video files only). width: Supported. (Image and video files only). duration: Supported. (Audio and video files only).

iOS Quirks Support for the MediaFileData properties is as follows:

codecs: Not supported. The attribute will always be null. bitrate: Supported on iOS4 devices for audio only. The attribute will always be 0 for image and video. height: Supported. (Image and video files only). width: Supported. (Image and video files only). duration: Supported. (Audio and video files only).

Connection The connection object gives access to the device's cellular and wifi connection information. This object is accessed under the navigator.network interface. Properties connection.type

Constants Connection.UNKNOWN Connection.ETHERNET Connection.WIFI Connection.CELL_2G Connection.CELL_3G Connection.CELL_4G Connection.NONE

connection.type Checks the active network connection that is being used. Description This property is a fast way to determine the device's network connection state, and type of connection. Supported Platforms iOS Android BlackBerry WebWorks (OS 5.0 and higher)

Quick Example function checkConnection() { var networkState = navigator.network.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.NONE] = 'No network connection'; alert('Connection type: ' + states[networkState]); } checkConnection();

Full Example navigator.network.connection.type Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { checkConnection(); } function checkConnection() { var networkState = navigator.network.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.NONE] = 'No network connection'; alert('Connection type: ' + states[networkState]); } A dialog box will report the network state.

Contacts The contacts object provides access to the device contacts database.

Methods contacts.create contacts.find

Arguments contactFields contactSuccess

Objects

contactError contactFindOptions

Contact ContactName ContactField ContactAddress ContactOrganization ContactFindOptions ContactError

contacts.create Returns a new Contact object. var contact = navigator.contacts.create(properties);

Description contacts.create is a synchronous function that returns a new Contact object. This method does not persist the Contact object to the device contacts database. To persist the Contact object to the device, invoke the Contact.save method. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example var myContact = navigator.contacts.create({"displayName": "Test User"});

Full Example Contact Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var myContact = navigator.contacts.create({"displayName": "Test User"}); myContact.gender = "male"; console.log("The contact, " + myContact.displayName + ", is of the " + myContact.gender + " gender");

} Example Create Contact

contacts.find Queries the device contacts database and returns one or more Contact objects, each containing the fields specified. navigator.contacts.find(contactFields, contactSuccess, contactError, contactFindOptions);

Description contacts.find is an asynchronous function that queries the device contacts database and returns an array of Contact objects. The resulting objects are passed to the contactSuccess callback function specified by the contactSuccess parameter. Users must specify the contact fields to be used as a search qualifier in the contactFields parameter. Only the fields specified in the contactFields parameter will be returned as properties of the Contact objects that are passed to the contactSuccess callback function. A zero-length contactFields parameter will result in an array of Contact objects with only the id property populated. A contactFields value of ["*"] will return 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 a match is found in a comparison with any of the specified fields, the contact is returned. Parameters

contactFields: Contact fields to be used as search qualifier. Only these fields will have values in the resulting Contact objects. (DOMString[]) [Required] contactSuccess: Success callback function that is invoked with the contacts returned from the contacts database. [Required] contactError: Error callback function. Invoked when error occurs. [Optional] contactFindOptions: Search options to filter contacts. [Optional]

Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example function onSuccess(contacts) {

alert('Found ' + contacts.length + ' contacts.'); }; function onError(contactError) { alert('onError!'); }; // find all contacts with 'Bob' in any name field var options = new ContactFindOptions(); options.filter="Bob"; var fields = ["displayName", "name"]; navigator.contacts.find(fields, onSuccess, onError, options);

Full Example Contact Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // find all contacts with 'Bob' in any name field var options = new ContactFindOptions(); options.filter="Bob"; var fields = ["displayName", "name"]; navigator.contacts.find(fields, onSuccess, onError, options); } // onSuccess: Get a snapshot of the current contacts // function onSuccess(contacts) { for (var i=0; i -1) { console.log((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); } ); }, 1000);

Full Example Media Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError); // Play audio

my_media.play(); // Update my_media position every second if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) { my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } Play Audio Pause Playing Audio Stop Playing Audio

media.getDuration Returns the duration of an audio file. media.getDuration();

Description Function media.getDuration is a synchronous function that returns the duration of the audio file in seconds, if known. If the duration is unknown, a value of -1 is returned. Supported Platforms Android iOS

Quick Example // Audio player // var my_media = new Media(src, onSuccess, onError); // Get duration var counter = 0; var timerDur = setInterval(function() { counter = counter + 100; if (counter > 2000) { clearInterval(timerDur); } var dur = my_media.getDuration(); if (dur > 0) { clearInterval(timerDur); document.getElementById('audio_duration').innerHTML = (dur) + " sec"; } }, 100);

Full Example Media Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError); // Play audio

my_media.play(); // Update my_media position every second if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) { my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } Play Audio Pause Playing Audio Stop Playing Audio

media.pause Pauses playing an audio file. media.pause();

Description Function media.pause is a synchronous function that pauses playing an audio file. Supported Platforms Android iOS

Quick Example // Play audio // function playAudio(url) { // Play the audio file at url var my_media = new Media(url, // success callback function() { console.log("playAudio():Audio Success"); }, // error callback function(err) { console.log("playAudio():Audio Error: "+err); }); // Play audio my_media.play(); // Pause after 10 seconds setTimeout(function() { media.pause(); }, 10000); }

Full Example Media Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) {

// Create Media object from src my_media = new Media(src, onSuccess, onError); // Play audio my_media.play(); // Update my_media position every second if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) { my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } Play Audio Pause Playing Audio Stop Playing Audio

media.play Starts or resumes playing an audio file. media.play();

Description Function media.play is a synchronous function that starts or resumes playing an audio file. Supported Platforms Android iOS

Quick Example // Play audio // function playAudio(url) { // Play the audio file at url var my_media = new Media(url, // success callback function() { console.log("playAudio():Audio Success"); }, // error callback function(err) { console.log("playAudio():Audio Error: "+err); }); // Play audio my_media.play(); }

Full Example Media Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) {

if (my_media == null) { // Create Media object from src my_media = new Media(src, onSuccess, onError); } // else play current audio // Play audio my_media.play(); // Update my_media position every second if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) { my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } Play Audio Pause Playing Audio Stop Playing Audio

media.release Releases the underlying operating systems audio resources. media.release();

Description Function media.release is a synchronous function that releases the underlying operating systems audio resources. This function is particularly important for Android as there are a finite amount of OpenCore instances for media playback. Developers should call the 'release' function when they no longer need the Media resource. Supported Platforms Android iOS

Quick Example // Audio player // var my_media = new Media(src, onSuccess, onError); my_media.play(); my_media.stop(); my_media.release();

Full Example Media Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError); // Play audio my_media.play(); // Update my_media position every second

if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) { my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } Play Audio Pause Playing Audio Stop Playing Audio

media.startRecord Starts recording an audio file. media.startRecord();

Description Function media.startRecord is a synchronous function that starts recording an audio file. Supported Platforms Android iOS

Quick Example // Record audio // function recordAudio() { var src = "myrecording.mp3"; var mediaRec = new Media(src, // success callback function() { console.log("recordAudio():Audio Success"); }, // error callback function(err) { console.log("recordAudio():Audio Error: "+ err.code); }); // Record audio mediaRec.startRecord(); }

Full Example Device Properties Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // Record audio // function recordAudio() { var src = "myrecording.mp3"; var mediaRec = new Media(src, onSuccess, onError); // Record audio mediaRec.startRecord(); // Stop recording after 10 sec var recTime = 0; var recInterval = setInterval(function() { recTime = recTime + 1; setAudioPosition(recTime + " sec"); if (recTime >= 10) { clearInterval(recInterval); mediaRec.stopRecord(); } }, 1000);

} // PhoneGap is ready // function onDeviceReady() { recordAudio(); } // onSuccess Callback // function onSuccess() { console.log("recordAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } Recording audio...

iOS Quirks The file to record to must already exist and should be of type .wav. The File API's can be used to create the file.

media.stop Stops playing an audio file. media.stop();

Description Function media.stop is a synchronous function that stops playing an audio file. Supported Platforms Android iOS

Quick Example // Play audio // function playAudio(url) { // Play the audio file at url var my_media = new Media(url, // success callback function() {

console.log("playAudio():Audio Success"); }, // error callback function(err) { console.log("playAudio():Audio Error: "+err); }); // Play audio my_media.play(); // Pause after 10 seconds setTimeout(function() { my_media.stop(); }, 10000); }

Full Example Media Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { playAudio("http://audio.ibeat.org/content/p1rj1s/p1rj1s_-_rockGuitar.mp3"); } // Audio player // var my_media = null; var mediaTimer = null; // Play audio // function playAudio(src) { // Create Media object from src my_media = new Media(src, onSuccess, onError); // Play audio my_media.play(); // Update my_media position every second if (mediaTimer == null) { mediaTimer = setInterval(function() { // get my_media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { setAudioPosition((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); } ); }, 1000); } } // Pause audio // function pauseAudio() { if (my_media) {

my_media.pause(); } } // Stop audio // function stopAudio() { if (my_media) { my_media.stop(); } clearInterval(mediaTimer); mediaTimer = null; } // onSuccess Callback // function onSuccess() { console.log("playAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) { document.getElementById('audio_position').innerHTML = position; } Play Audio Pause Playing Audio Stop Playing Audio

media.stopRecord Stops recording an audio file. media.stopRecord();

Description Function media.stopRecord is a synchronous function that stops recording an audio file. Supported Platforms Android iOS

Quick Example // Record audio // function recordAudio() {

var src = "myrecording.mp3"; var mediaRec = new Media(src, // success callback function() { console.log("recordAudio():Audio Success"); }, // error callback function(err) { console.log("recordAudio():Audio Error: "+ err.code); }); // Record audio mediaRec.startRecord(); // Stop recording after 10 seconds setTimeout(function() { mediaRec.stopRecord(); }, 10000); }

Full Example Device Properties Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // Record audio // function recordAudio() { var src = "myrecording.mp3"; var mediaRec = new Media(src, onSuccess, onError); // Record audio mediaRec.startRecord(); // Stop recording after 10 sec var recTime = 0; var recInterval = setInterval(function() { recTime = recTime + 1; setAudioPosition(recTime + " sec"); if (recTime >= 10) { clearInterval(recInterval); mediaRec.stopRecord(); } }, 1000); } // PhoneGap is ready // function onDeviceReady() { recordAudio(); } // onSuccess Callback // function onSuccess() { console.log("recordAudio():Audio Success"); } // onError Callback // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Set audio position // function setAudioPosition(position) {

document.getElementById('audio_position').innerHTML = position; } Recording audio...

MediaError A MediaError object is returned to the mediaError callback function when an error occurs. Properties

code: One of the predefined error codes listed below. message: Error message describing the details of the error.

Constants

MediaError.MEDIA_ERR_ABORTED MediaError.MEDIA_ERR_NETWORK MediaError.MEDIA_ERR_DECODE MediaError.MEDIA_ERR_NONE_SUPPORTED

Description The MediaError object is returned to the user through the mediaError callback function when an error occurs.

mediaError A user specified callback function that is invoked when there is an error in media functions. function(error) { // Handle the error }

Parameters

error: The error returned by the device. (MediaError)

Notification Visual, audible, and tactile device notifications.

Methods notification.alert notification.confirm notification.beep notification.vibrate

notification.alert Shows a custom alert or dialog box. 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, Default: "Alert") buttonName: Button name (String) (Optional, Default: "OK")

Description Most PhoneGap implementations use a native dialog box for this feature. However, some platforms simply use the browser's alert function, which is typically less customizable. Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // Android / BlackBerry WebWorks (OS 5.0 and higher) / iPhone // function alertDismissed() { // do something } navigator.notification.alert( 'You are the winner!', // message alertDismissed, // callback 'Game Over', // title 'Done' // buttonName ); // BlackBerry (OS 4.6) / webOS // navigator.notification.alert('You are the winner!');

Full Example Notification Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // Empty } // alert dialog dismissed function alertDismissed() { // do something } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message alertDismissed, // callback 'Game Over', // title 'Done' // buttonName ); } Show Alert

notification.confirm Shows 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). (Number) title: Dialog title (String) (Optional, Default: "Confirm") buttonLabels: Comma separated string with button labels (String) (Optional, Default: "OK,Cancel")

Description Function notification.confirm displays a native dialog box that is more customizable than the browser's confirm function.

Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // process the confirmation dialog result function onConfirm(button) { alert('You selected button ' + button); } // Show a custom confirmation dialog // function showConfirm() { navigator.notification.confirm( 'You are the winner!', // message onConfirm, // callback to invoke with index of button pressed 'Game Over', // title 'Restart,Exit' // buttonLabels ); }

Full Example Notification Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // Empty } // process the confirmation dialog result function onConfirm(button) { alert('You selected button ' + button); } // Show a custom confirmation dialog // function showConfirm() { navigator.notification.confirm( 'You are the winner!', // message onConfirm, // callback to invoke with index of button pressed 'Game Over', // title 'Restart,Exit' // buttonLabels ); } Show Confirm

notification.beep The device will play a beep sound. navigator.notification.beep(times);

times: The number of times to repeat the beep (Number)

Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // Beep twice! navigator.notification.beep(2);

Full Example Notification Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // Empty } // Show a custom alert // function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } Show Alert Play Beep Vibrate

Android Quirks Android plays the default "Notification ringtone" specified under the "Settings/Sound & Display" panel.

iPhone Quirks Ignores the beep count argument. There is no native beep API for iPhone. PhoneGap implements beep by playing an audio file via the media API. The user must provide a file with the desired beep tone. This file must be less than 30 seconds long, located in the www/ root, and must be named beep.wav.

notification.vibrate Vibrates the device for the specified amount of time. navigator.notification.vibrate(milliseconds)

time: Milliseconds to vibrate the device. 1000 milliseconds equals 1 second (Number)

Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // Vibrate for 2.5 seconds // navigator.notification.vibrate(2500);

Full Example Notification Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // Empty } // Show a custom alert

// function showAlert() { navigator.notification.alert( 'You are the winner!', // message 'Game Over', // title 'Done' // buttonName ); } // Beep three times // function playBeep() { navigator.notification.beep(3); } // Vibrate for 2 seconds // function vibrate() { navigator.notification.vibrate(2000); } Show Alert Play Beep Vibrate

iPhone Quirks

time: Ignores the time and vibrates for a pre-set amount of time. navigator.notification.vibrate(); navigator.notification.vibrate(2500); // 2500 is ignored

Storage Provides access to the devices storage options.

This API is based on the W3C Web SQL Database Specification and W3C Web Storage API Specification. Some devices already provide an implementation of this spec. For those devices, the built-in support is used instead of replacing it with PhoneGap's implementation. For devices that don't have storage support, PhoneGap's implementation should be compatible with the W3C specification. Methods openDatabase

Arguments name version display_name size

Objects Database SQLTransaction SQLResultSet SQLResultSetList SQLError localStorage

openDatabase Returns a new Database object. var dbShell = window.openDatabase(name, version, display_name, size);

Description window.openDatabase returns a new Database object. This method will create a new SQL Lite Database and return a Database object. Use the Database Object to manipulate the data. Supported Platforms Android BlackBerry WebWorks (OS 6.0 and higher) iPhone

Quick Example var db = window.openDatabase("test", "1.0", "Test DB", 1000000);

Full Example Contact Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var db = window.openDatabase("test", "1.0", "Test DB", 1000000); } Example Open Database

name The name of the database.

version The version of the database.

display_name The display name of the database.

size The size of the database in bytes.

Database Contains methods that allow the user to manipulate the Database Methods

transaction: Runs a database transaction. changeVersion: method allows scripts to atomically verify the version number and change it at the same time as doing a schema update.

Details A Database object is returned from a call to window.openDatabase(). Supported Platforms Android BlackBerry WebWorks (OS 6.0 and higher) iPhone

Transaction Quick Example function populateDB(tx) { tx.executeSql('DROP TABLE IF EXISTS DEMO'); tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")'); } function errorCB(err) { alert("Error processing SQL: "+err.code); } function successCB() { alert("success!"); } var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(populateDB, errorCB, successCB);

Change Version Quick Example var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.changeVersion("1.0", "1.1");

Full Example Contact Example // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(populateDB, errorCB, successCB); } // Populate the database // function populateDB(tx) { tx.executeSql('DROP TABLE IF EXISTS DEMO'); tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")'); } // Transaction error callback // function errorCB(tx, err) { alert("Error