You are on page 1of 144

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 <!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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!'); } </script> </head> <body> <h1>Example</h1> <p>getCurrentAcceleration</p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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 + '<br />' + 'Acceleration Y: ' + acceleration.y + '<br />' + 'Acceleration Z: ' + acceleration.z + '<br />' + 'Timestamp: ' + acceleration.timestamp + '<br />'; } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } </script> </head> <body> <div id="accelerometer">Waiting for accelerometer...</div> </body> </html>

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 <!DOCTYPE html>

<html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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 + '<br />' + 'Acceleration Y: ' + acceleration.y + '<br />' + 'Acceleration Z: ' + acceleration.z + '<br />' + 'Timestamp: ' + acceleration.timestamp + '<br />'; } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } </script> </head> <body> <div id="accelerometer">Waiting for accelerometer...</div> <button onclick="stopWatch();">Stop Watching</button> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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!'); } </script> </head> <body> <h1>Example</h1> <p>getCurrentAcceleration</p> </body> </html>

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 <img> 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 <!DOCTYPE html> <html> <head> <title>Capture Photo</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> 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); } </script> </head> <body> <button onclick="capturePhoto();">Capture Photo</button> <br> <button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br> <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br> <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br> <img style="display:none;width:60px;height:60px;" id="smallImage" src="" /> <img style="display:none;" id="largeImage" src="" /> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Capture Audio</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8" src="json2.js"></script> <script type="text/javascript" charset="utf-8"> // 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 }); } </script> </head> <body> <button onclick="captureAudio();">Capture Audio</button> <br> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Capture Image</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8" src="json2.js"></script> <script type="text/javascript" charset="utf-8">

// 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 }); } </script> </head> <body> <button onclick="captureImage();">Capture Image</button> <br> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Capture Video</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8" src="json2.js"></script> <script type="text/javascript" charset="utf-8"> // 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 }); } </script> </head> <body> <button onclick="captureVideo();">Capture Video</button> <br>

</body> </html>

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 <!DOCTYPE html> <html> <head> <title>Capture Audio</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8" src="json2.js"></script> <script type="text/javascript" charset="utf-8"> // 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 }); } </script> </head> <body> <button onclick="captureAudio();">Capture Audio</button> <br> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Capture Image</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8" src="json2.js"></script> <script type="text/javascript" charset="utf-8">

// 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 }); } </script> </head> <body> <button onclick="captureImage();">Capture Image</button> <br> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Capture Video</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8" src="json2.js"></script> <script type="text/javascript" charset="utf-8"> // 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 }); } </script> </head> <body> <button onclick="captureVideo();">Capture Video</button> <br>

</body> </html>

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 <!DOCTYPE html> <html> <head> <title>navigator.network.connection.type Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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]); } </script> </head> <body> <p>A dialog box will report the network state.</p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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");

} </script> </head> <body> <h1>Example</h1> <p>Create Contact</p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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<contacts.length; i++) { console.log("Display Name = " + contacts[i].displayName); } } // onError: Failed to get the contacts // function onError(contactError) { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>Find Contacts</p> </body> </html>

Contact Contains properties that describe a contact, such as a user's personal or business contact. Properties

id: A globally unique identifier. (DOMString)

displayName: The name of this Contact, suitable for display to end-users. (DOMString) name: An object containing all components of a persons name. (ContactName) nickname: A casual name to address the contact by. (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. (ContactAddresses[]) 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 contacts user defined categories. (ContactField[]) urls: An array of web pages associated to the contact. (ContactField[])

Methods

clone: Returns a new Contact object that is a deep copy of the calling object, with the id property set to null. remove: Removes the contact from the device contacts database. An error callback is called with a ContactError object if the removal is unsuccessful. save: Saves a new contact to the device contacts database, or updates an existing contact if a contact with the same id already exists.

Details The Contact object represents a user contact. Contacts can be created, saved to, or removed from the device contacts database. Contacts can also be retrieved (individually or in bulk) from the database by invoking the contacts.find method. Note: Not all of the above contact fields are supported on every device platform. Please check each platform's Quirks section for information about which fields are supported. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Save Quick Example function onSuccess(contact) { alert("Save Success"); }; function onError(contactError) { alert("Error = " + contactError.code); }; // create a new contact object var contact = navigator.contacts.create(); contact.displayName = "Plumber"; contact.nickname = "Plumber"; //specify both to support all devices // populate some fields var name = new ContactName(); name.givenName = "Jane"; name.familyName = "Doe"; contact.name = name; // save to device contact.save(onSuccess,onError);

Clone Quick Example // clone the contact object var clone = contact.clone(); clone.name.givenName = "John"; console.log("Original contact name = " + contact.name.givenName); console.log("Cloned contact name = " + clone.name.givenName);

Remove Quick Example function onSuccess() { alert("Removal Success"); }; function onError(contactError) { alert("Error = " + contactError.code); }; // remove the contact from the device contact.remove(onSuccess,onError);

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // create var contact = navigator.contacts.create(); contact.displayName = "Plumber"; contact.nickname = "Plumber"; //specify both to support all devices var name = new ContactName(); name.givenName = "Jane"; name.familyName = "Doe"; contact.name = name; // save contact.save(onSaveSuccess,onSaveError); // clone

var clone = contact.clone(); clone.name.givenName = "John"; console.log("Original contact name = " + contact.name.givenName); console.log("Cloned contact name = " + clone.name.givenName); // remove contact.remove(onRemoveSuccess,onRemoveError); } // onSaveSuccess: Get a snapshot of the current contacts // function onSaveSuccess(contact) { alert("Save Success"); } // onSaveError: Failed to get the contacts // function onSaveError(contactError) { alert("Error = " + contactError.code); } // onRemoveSuccess: Get a snapshot of the current contacts // function onRemoveSuccess(contacts) { alert("Removal Success"); } // onRemoveError: Failed to get the contacts // function onRemoveError(contactError) { alert("Error = " + contactError.code); } </script> </head> <body> <h1>Example</h1> <p>Find Contacts</p> </body> </html>

Android 2.X Quirks

categories: This property is not support by Android 2.X devices, and will always be returned as null.

Android 1.X Quirks

name: This property is not support by Android 1.X devices, and will always be returned as null. nickname: This property is not support by Android 1.X devices, and will always be returned as null. birthday: This property is not support by Android 1.X devices, and will always be returned as null. photos: This property is not support by Android 1.X devices, and will always be returned as null. categories: This property is not support by Android 1.X devices, and will always be returned as null. urls: This property is not support by Android 1.X devices, and will always be returned as null.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

id: Supported. Assigned by device when contact is saved. displayName: Supported. Stored in BlackBerry user1 field.

nickname: This property is not supported, and will always be returned as null. phoneNumbers: Partially supported. Phone numbers will be stored in BlackBerry fields homePhone1 and homePhone2 if type is 'home', workPhone1 and workPhone2 if type is 'work', mobilePhone if type is 'mobile', faxPhone if type is 'fax', pagerPhone if type is 'pager', and otherPhone if type is none of the above.

emails: Partially supported. The first three email addresses will be stored in the BlackBerry email1, email2, and email3 fields, respectively. addresses: Partially supported. The first and second addresses will be stored in the BlackBerry homeAddress and workAddress fields, respectively. ims: This property is not supported, and will always be returned as null. organizations: Partially supported. The name and title of the first organization are stored in the BlackBerry company and title fields, respectively. photos: - Partially supported. A single thumbnail-sized photo is supported. To set a contact's photo, pass in a either a Base64 encoded image, or a URL pointing to the image. The image will be scaled down before saving to the BlackBerry contacts database. The contact photo is returned as a Base64 encoded image.

categories: Partially supported. Only 'Business' and 'Personal' categories are supported. urls: Partially supported. The first url is stored in BlackBerry webpage field.

iOS Quirks

displayName: This property is not supported by iOS and will be returned as null unless there is no ContactName specified. If there is no ContactName, then composite name, nickame or "" is returned for displayName, respectively.

birthday: For input, this property must be provided as a JavaScript Date object. It is returned as a JavaScript Date object. photos: Returned Photo is stored in the application's temporary directory and a File URL to photo is returned. Contents of temporary folder is deleted when application exits. categories: This property is not currently supported and will always be returned as null.

ContactAddress Contains address properties for a Contact object. Properties

pref: Set to true if this ContactAddress contains the user's preferred value. (boolean)


Details

type: A string that tells you what type of field this is (example: 'home'). _(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)

The ContactAddress object stores the properties of a single address of a contact. A Contact object can have one or more addresses in a ContactAddress[] array. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // display the address information for all contacts function onSuccess(contacts) { for (var i=0; i<contacts.length; i++) { for (var j=0; j<contacts[i].addresses.length; j++) { alert("Pref: " + contacts[i].addresses[j].pref + "\n" + "Type: " + contacts[i].addresses[j].type + "\n" + "Formatted: " + contacts[i].addresses[j].formatted + "\n" + "Street Address: " + contacts[i].addresses[j].streetAddress + "\n" + "Locality: " + contacts[i].addresses[j].locality + "\n" + "Region: " + contacts[i].addresses[j].region + "\n" + "Postal Code: " + contacts[i].addresses[j].postalCode + "\n" + "Country: " + contacts[i].addresses[j].country); } } }; function onError(contactError) { alert('onError!'); }; // find all contacts var options = new ContactFindOptions(); options.filter=""; var filter = ["displayName","addresses"]; navigator.contacts.find(filter, onSuccess, onError, options);

Full Example <!DOCTYPE html> <html> <head>

<title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // find all contacts var options = new ContactFindOptions(); options.filter=""; var filter = ["displayName","addresses"]; navigator.contacts.find(filter, onSuccess, onError, options); } // onSuccess: Get a snapshot of the current contacts // function onSuccess(contacts) { // display the address information for all 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); } } }; // onError: Failed to get the contacts // function onError(contactError) { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>Find Contacts</p> </body> </html>

Android 2.X Quirks

pref: This property is not supported by Android 2.X devices and will always return false.

Android 1.X Quirks

pref: This property is not supported by Android 1.X devices and will always return false. type: This property is not supported by Android 1.X devices and will always return null. streetAddress: This property is not support by Android 1.X devices, and will always return null. locality: This property is not support by Android 1.X devices, and will always return null. region: This property is not support by Android 1.X devices, and will always return null.

postalCode: This property is not support by Android 1.X devices, and will always return null. country: This property is not support by Android 1.X devices, and will always return null.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

pref: This property is not supported on Blackberry devices and will always return false. type: Partially supported. Only one each of "Work" and "Home" type addresses can be stored per contact. formatted: Partially supported. Will return concatenation of all BlackBerry address fields. streetAddress: Supported. Will return 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.

iOS Quirks

pref: This property is not supported on iOS devices and will always return false. formatted: Not currently supported.

ContactField Supports generic fields in a Contact object. Some properties that are stored as ContactField objects include email addresses, phone numbers, and urls. Properties


Details

type: A string that tells you what type of field this is (example: 'home'). (DOMString) value: The value of the field (such as a phone number or email address). (DOMString) pref: Set to true if this ContactField contains the user's preferred value. (boolean)

The ContactField object is a reusable component that is used to support contact fields in a generic fashion. Each ContactField object contains a value property, a type property, and a 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 the type attribute of a ContactField object. For example, a phone number can have type values of 'home', 'work', 'mobile', 'iPhone', or any other value that is supported by the contact database on a particular device platform. However, in the case of the Contact photos field, PhoneGap makes use of the type field to indicate the format of the returned image. PhoneGap will return type: 'url' when the value attribute contains a URL to the photo image, or type: 'base64' when the returned value attribute contains a Base64 encoded image string. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // create a new contact var contact = navigator.contacts.create(); // store contact phone numbers in ContactField[] var phoneNumbers = [3]; 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();

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // create a new contact var contact = navigator.contacts.create(); // store contact phone numbers in ContactField[] var phoneNumbers = [3]; 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(); // search contacts, returning display name and phone numbers var options = new ContactFindOptions(); options.filter=""; filter = ["displayName","phoneNumbers"]; navigator.contacts.find(filter, onSuccess, onError, options); } // onSuccess: Get a snapshot of the current contacts // function onSuccess(contacts) { for (var i=0; i<contacts.length; i++) { // display phone numbers for (var j=0; j<contacts[i].phoneNumbers.length; j++) {

alert("Type: " + contacts[i].phoneNumbers[j].type + "\n" + "Value: " + contacts[i].phoneNumbers[j].value + "\n" + "Preferred: " + contacts[i].phoneNumbers[j].pref); } } }; // onError: Failed to get the contacts // function onError(contactError) { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>Find Contacts</p> </body> </html>

Android Quirks

pref: This property is not support by Android devices, and will always return false.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

type: Partially supported. Used for phone numbers. value: Supported. pref: This property is not supported, and will always return false.

iOS Quirks

pref: This property is not supported on iOS devices and will always return false.

ContactFindOptions Contains properties that can be used to filter the results of a contacts.find operation. Properties

filter: The search string used to find contacts. (DOMString) (Default: "") multiple: Determines if the find operation should return multiple contacts. (Boolean) (Default: false)

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

Quick Example // success callback function onSuccess(contacts) { for (var i=0; i<contacts.length; i++) { alert(contacts[i].displayName); } }; // error callback function onError(contactError) { alert('onError!'); }; // specify contact search criteria var options = new ContactFindOptions(); options.filter=""; // empty search string returns all contacts options.multiple=true; // return multiple results filter = ["displayName"]; // return contact.displayName field // find contacts navigator.contacts.find(filter, onSuccess, onError, options);

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // specify contact search criteria var options = new ContactFindOptions(); options.filter=""; // empty search string returns all contacts options.multiple=true; // return multiple results filter = ["displayName"]; // return contact.displayName field // find contacts navigator.contacts.find(filter, onSuccess, onError, options); } // onSuccess: Get a snapshot of the current contacts // function onSuccess(contacts) { for (var i=0; i<contacts.length; i++) { alert(contacts[i].displayName); } }; // onError: Failed to get the contacts // function onError(contactError) { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>Find Contacts</p> </body> </html>

ContactName Contains name properties of a Contact object. Properties


Details

formatted: The complete name of the contact. (DOMString) familyName: The contacts family name. (DOMString) givenName: The contacts given name. (DOMString) middleName: The contacts middle name. (DOMString) honorificPrefix: The contacts prefix (example Mr. or Dr.) (DOMString) honorificSuffix: The contacts suffix (example Esq.). (DOMString)

The ContactName object stores name properties of a contact. Supported Platforms Android 2.X BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example function onSuccess(contacts) { for (var i=0; i<contacts.length; i++) { alert("Formatted: " + contacts[i].name.formatted + "\n" + "Family Name: " + contacts[i].name.familyName + "\n" + "Given Name: " + contacts[i].name.givenName + "\n" + "Middle Name: " + contacts[i].name.middleName + "\n" + "Suffix: " + contacts[i].name.honorificSuffix + "\n" + "Prefix: " + contacts[i].name.honorificSuffix); } }; function onError(contactError) { alert('onError!'); }; var options = new ContactFindOptions(); options.filter=""; filter = ["displayName","name"]; navigator.contacts.find(filter, onSuccess, onError, options);

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load //

document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var options = new ContactFindOptions(); options.filter=""; filter = ["displayName","name"]; navigator.contacts.find(filter, onSuccess, onError, options); } // onSuccess: Get a snapshot of the current contacts // 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.honorificPrefix); } }; // onError: Failed to get the contacts // function onError(contactError) { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>Find Contacts</p> </body> </html>

Android Quirks

formatted: Partially supported. Will return the concatenation of honorificPrefix, givenName, middleName, familyName and honorificSuffix but will not store.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

formatted: Partially supported. Will return concatenation of BlackBerry firstName and lastName fields. familyName: Supported. Stored in BlackBerry lastName field. givenName: Supported. Stored in BlackBerry firstName field. middleName: This property is not supported, and will always return null. honorificPrefix: This property is not supported, and will always return null. honorificSuffix: This property is not supported, and will always return null.

iOS Quirks

formatted: Partially supported. Will return iOS Composite Name but will not store.

ContactOrganization Contains organization properties of a Contact object. Properties


Details

pref: Set to true if this ContactOrganization contains the user's preferred value. (boolean) type: A string that tells you what type of field this is (example: 'home'). _(DOMString) name: The name of the organization. (DOMString) department: The department the contract works for. (DOMString) title: The contacts title at the organization. (DOMString)

The ContactOrganization object stores a contact's organization properties. A Contact object stores one or more ContactOrganization objects in an array. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example function onSuccess(contacts) { for (var i=0; i<contacts.length; i++) { for (var j=0; j<contacts[i].organizations.length; j++) { alert("Pref: " + contacts[i].organizations[j].pref + "\n" + "Type: " + contacts[i].organizations[j].type + "\n" + "Name: " + contacts[i].organizations[j].name + "\n" + "Department: " + contacts[i].organizations[j].department + "\n" + "Title: " + contacts[i].organizations[j].title); } } }; function onError(contactError) { alert('onError!'); }; var options = new ContactFindOptions(); options.filter=""; filter = ["displayName","organizations"]; navigator.contacts.find(filter, onSuccess, onError, options);

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load //

document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var options = new ContactFindOptions(); options.filter=""; filter = ["displayName","organizations"]; navigator.contacts.find(filter, onSuccess, onError, options); } // onSuccess: Get a snapshot of the current contacts // 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); } } }; // onError: Failed to get the contacts // function onError(contactError) { alert('onError!'); } </script> </head> <body> <h1>Example</h1> <p>Find Contacts</p> </body> </html>

Android 2.X Quirks

pref: This property is not supported by Android 2.X devices and will always return false.

Android 1.X Quirks

pref: This property is not supported by Android 1.X devices and will always return false. type: This property is not supported by Android 1.X devices and will always return null. title: This property is not supported by Android 1.X devices, and will always be returned as null.

BlackBerry WebWorks (OS 5.0 and higher) Quirks

pref: This property is not supported by Blackberry devices and will always return false. type: This property is not supported by Blackberry devices and will always return null. name: Partially supported. The first organization name will be stored in the BlackBerry company field. department: This property is not supported, and will always be returned as null. title: Partially supported. The first organization title will be stored in the BlackBerry jobTitle field.

iOS Quirks

pref: This property is not supported on iOS devices and will always return false. type: This property is not supported on iOS devices and will always return null. name: Partially supported. The first organization name will be stored in the iOS kABPersonOrganizationProperty field. department: Partially supported. The first department name will be stored in the iOS kABPersonDepartmentProperty field. title: Partially supported. The first title will be stored in the iOS kABPersonJobTitleProperty field.

ContactError A ContactError object is returned to the contactError callback when an error occurs. Properties

code: One of the predefined error codes listed below.

Constants

ContactError.UNKNOWN_ERROR ContactError.INVALID_ARGUMENT_ERROR ContactError.TIMEOUT_ERROR ContactError.PENDING_OPERATION_ERROR ContactError.IO_ERROR ContactError.NOT_SUPPORTED_ERROR ContactError.PERMISSION_DENIED_ERROR

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

contactSuccess Success callback function that provides the Contact array resulting from a contacts.find operation. function(contacts) {

// Do something }

Parameters

contacts: The contact array resulting from a find operation. (Contact)

Example function contactSuccess(contacts) { for (var i=0; i<contacts.length; i++) { console.log("Display Name = " + contacts[i].displayName; }

contactError Error callback function for contact functions. function(error) { // Handle the error }

contactFields Required parameter of the contacts.find method. Use this parameter to specify which fields should be included in the Contact objects resulting from a find operation. ["name", "phoneNumbers", "emails"]

contactFindOptions Optional parameter of the contacts.find method. Use this parameter to filter the contacts returned from the contacts database. { filter: "", multiple: true, };

Options


Device

filter: The search string used to filter contacts. (DOMString) (Default: "") multiple: Determines if the find operation should return multiple contacts. (Boolean) (Default: false)

The device object describes the device's hardware and software.

Properties device.name device.phonegap device.platform device.uuid device.version

Variable Scope Since device is assigned to the window object, it is implicitly in the global scope. // These reference the same `device` // var phoneName = window.device.name; var phoneName = device.name;

device.name Get the device's model name. var string = device.name;

Description device.name returns the name of the device's model or product. This value is set by the device manufacturer and may be different across versions of the same product. Supported Platforms Android BlackBerry BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // Android: Nexus One returns "Passion" (Nexus One code name) // Motorola Droid returns "voles" // BlackBerry: Bold 8900 returns "8900" // iPhone: All devices returns a name set by iTunes e.g. "Joe's iPhone" // var name = device.name;

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8">

// Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device PhoneGap: ' + device.phonegap + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>

Android Quirks Gets the product name instead of the model name. iPhone Quirks Gets the device's custom name instead of the device model name. The custom name is set by the owner in iTunes. e.g. "Joe's iPhone" The product name is often the code name given during production. e.g. Nexus One returns "Passion", Motorola Droid returns "voles"

device.phonegap Get the version of phonegap running on the device. var string = device.phonegap;

Description device.phonegap returns the version of phonegap running on the device. Supported Platforms Android BlackBerry BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example var name = device.phonegap;

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device PhoneGap: ' + device.phonegap + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>

device.platform Get the device's operating system name. var string = device.platform;

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

Quick Example // Depending on the device, a few examples are: // - "Android" // - "BlackBerry" // - "iPhone" // - "webOS" // var devicePlatform = device.platform;

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device PhoneGap: ' + device.phonegap + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>

iPhone Quirks All devices return iPhone as the platform. This is inaccurate because Apple has rebranded the iPhone operating system as iOS. BlackBerry Quirks Devices may return the device platform version instead of the platform name. For example, the Storm2 9550 would return '2.13.0.95' or similar.

device.uuid Get the device's Universally Unique Identifier (UUID). var string = device.uuid;

Description The details of how a UUID is generated are determined by the device manufacturer and specific to the device's platform or model.

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

Quick Example // Android: Returns a random 64-bit integer (as a string, again!) // The integer is generated on the device's first boot // // BlackBerry: Returns the PIN number of the device // This is a nine-digit unique integer (as a string, though!) // // iPhone: (Paraphrased from the UIDevice Class documentation) // Returns a string of hash values created from multiple hardware identifies. // It is guaranteed to be unique for every device and cannot be tied // to the user account. // var deviceID = device.uuid;

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device PhoneGap: ' + device.phonegap + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>

device.version Get the operating system version. var string = device.version;

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

Quick Example // Android: Froyo OS would return "2.2" // Eclair OS would return "2.1", "2.0.1", or "2.0" // Version can also return update level "2.1-update1" // // BlackBerry: Bold 9000 using OS 4.6 would return "4.6.0.282" // // iPhone: iOS 3.2 returns "3.2" // var deviceVersion = device.version;

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var element = document.getElementById('deviceProperties'); element.innerHTML = 'Device Name: ' + device.name + '<br />' + 'Device PhoneGap: ' + device.phonegap + '<br />' + 'Device Platform: ' + device.platform + '<br />' + 'Device UUID: ' + device.uuid + '<br />' + 'Device Version: ' + device.version + '<br />'; } </script> </head> <body> <p id="deviceProperties">Loading device properties...</p> </body> </html>

Events PhoneGap lifecycle events.

Event Types backbutton

deviceready menubutton pause resume searchbutton online offline

backbutton This is an event that fires when the user presses the back button on Android. document.addEventListener("backbutton", yourCallbackFunction, false);

Details If you need to over ride the default back button behaviour on Android you can register and event listenter for the 'backbutton' event. It is no longer necessary to call any other method to over ride the back button behaviour. Now, you only need to register an event listener for 'backbutton'. Typically, you will want to attach an event listener with document.addEventListener once you receive the PhoneGap 'deviceready' event. Supported Platforms Android

Quick Example document.addEventListener("backbutton", onBackKeyDown, false); function onBackKeyDown() { // Handle the back buton }

Full Example <!DOCTYPE html> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. // // At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { // Register the event listener document.addEventListener("backbutton", onBackKeyDown, false);

} // Handle the back button // function onBackKeyDown() { } </script> </head> <body> </body> </html>

deviceready This is an event that fires when PhoneGap is fully loaded. document.addEventListener("deviceready", yourCallbackFunction, false);

Details This is a very important event that every PhoneGap application should use. PhoneGap consists of two code bases: native and JavaScript. While the native code is loading, a custom loading image is displayed. However, JavaScript is only loaded once the DOM loads. This means your web application could, potentially, call a PhoneGap JavaScript function before it is loaded. The PhoneGap deviceready event fires once PhoneGap has fully loaded. After the device has fired, you can safely make calls to PhoneGap function. Typically, you will want to attach an event listener with document.addEventListener once the HTML document's DOM has loaded. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Now safe to use the PhoneGap API }

Full Example <!DOCTYPE html> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. //

// At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { // Now safe to use the PhoneGap API } </script> </head> <body> </body> </html>

BlackBerry (OS 4.6) Quirks Custom events are not supported in the RIM BrowserField (web browser view), so the deviceready event will never fire. A workaround is to manually query PhoneGap.available until PhoneGap has fully loaded. function onLoad() { // BlackBerry OS 4 browser does not support events. // So, manually wait until PhoneGap is available. // var intervalID = window.setInterval( function() { if (PhoneGap.available) { window.clearInterval(intervalID); onDeviceReady(); } }, 500 ); } function onDeviceReady() { // Now safe to use the PhoneGap API }

menubutton This is an event that fires when the user presses the menu button on Android. document.addEventListener("menubutton", yourCallbackFunction, false);

Details If you need to over ride the default menu button behaviour on Android you can register and event listenter for the 'menubutton' event. Typically, you will want to attach an event listener with document.addEventListener once you receive the PhoneGap 'deviceready' event.

Supported Platforms Android

Quick Example document.addEventListener("menubutton", onMenuKeyDown, false); function onMenuKeyDown() { // Handle the back buton }

Full Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. // // At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { // Register the event listener document.addEventListener("menubutton", onMenuKeyDown, false); } // Handle the menu button // function onMenuKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>

pause This is an event that fires when a PhoneGap application is put into the background. document.addEventListener("pause", yourCallbackFunction, false);

Details PhoneGap consists of two code bases: native and JavaScript. While the native code puts the application into the background the pause event is fired. Typically, you will want to attach an event listener with document.addEventListener once you receive the PhoneGap

'deviceready' event. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example document.addEventListener("pause", onPause, false); function onPause() { // Handle the pause event }

Full Example <!DOCTYPE html> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. // // At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { document.addEventListener("pause", onPause, false); } // Handle the pause event // function onPause() { } </script> </head> <body> </body> </html>

iOS Quirks In the pause handler, any calls that go through Objective-C will not work, nor will any calls that are interactive, like alerts. This means that you cannot call console.log (and its variants), or any calls from Plugins or the PhoneGap API. These will only be processed when the app resumes (processed on the next run-loop).

resume This is an event that fires when a PhoneGap application is retrieved from the background. document.addEventListener("resume", yourCallbackFunction, false);

Details PhoneGap consists of two code bases: native and JavaScript. While the native code pulls the application from the background the resume event is fired. Typically, you will want to attach an event listener with document.addEventListener once you receive the PhoneGap 'deviceready' event. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example document.addEventListener("resume", onResume, false); function onResume() { // Handle the pause event }

Full Example <!DOCTYPE html> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. // // At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { document.addEventListener("resume", onResume, false); } // Handle the resume event // function onResume() { } </script> </head> <body> </body> </html>

online This is an event that fires when a PhoneGap application is online (connected to the Internet). document.addEventListener("online", yourCallbackFunction, false);

Details When the application's network connection changes to being online, the online event is fired. Typically, you will want to attach an event listener with document.addEventListener once you receive the PhoneGap 'deviceready' event. Supported Platforms iOS Android BlackBerry WebWorks (OS 5.0 and higher)

Quick Example document.addEventListener("online", onOnline, false); function onOnline() { // Handle the online event }

Full Example <!DOCTYPE html> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. // // At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { document.addEventListener("online", onOnline, false); } // Handle the online event // function onOnline() { } </script> </head> <body> </body> </html>

iOS Quirks During initial startup, the first online event (if applicable) will take at least a second to fire.

offline This is an event that fires when a PhoneGap application is offline (not connected to the Internet).

document.addEventListener("offline", yourCallbackFunction, false);

Details When the application's network connection changes to being offline, the offline event is fired. Typically, you will want to attach an event listener with document.addEventListener once you receive the PhoneGap 'deviceready' event. Supported Platforms iOS Android BlackBerry WebWorks (OS 5.0 and higher)

Quick Example document.addEventListener("offline", onOffline, false); function onOffline() { // Handle the offline event }

Full Example <!DOCTYPE html> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. // // At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { document.addEventListener("offline", onOffline, false); } // Handle the offline event // function onOffline() { } </script> </head> <body> </body> </html>

iOS Quirks During initial startup, the first offline event (if applicable) will take at least a second to fire.

searchbutton This is an event that fires when the user presses the search button on Android. document.addEventListener("searchbutton", yourCallbackFunction, false);

Details If you need to over ride the default search button behaviour on Android you can register and event listenter for the 'searchbutton' event. Typically, you will want to attach an event listener with document.addEventListener once you receive the PhoneGap 'deviceready' event. Supported Platforms Android

Quick Example document.addEventListener("searchbutton", onSearchKeyDown, false); function onSearchKeyDown() { // Handle the back buton }

Full Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>PhoneGap Device Ready Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Call onDeviceReady when PhoneGap is loaded. // // At this point, the document has loaded but phonegap.js has not. // When PhoneGap is loaded and talking with the native device, // it will call the event `deviceready`. // function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } // PhoneGap is loaded and it is now safe to make calls PhoneGap methods // function onDeviceReady() { // Register the event listener document.addEventListener("searchbutton", onSearchKeyDown, false); } // Handle the search button // function onSearchKeyDown() { } </script> </head> <body onload="onLoad()"> </body> </html>

File An API to read, write and navigate file system hierarchies.

Objects DirectoryEntry DirectoryReader File FileEntry FileError FileReader FileSystem FileTransfer FileTransferError FileUploadOptions FileUploadResult FileWriter Flags LocalFileSystem Metadata

File This object contains attributes of a single file. Properties


Details

name: The name of the file. (DOMString) fullPath: The full path of the file including the file name. (DOMString) type: The mime type of the file. (DOMString) lastModifiedDate: The last time the file was modified. (Date) size: The size of the file in bytes. (long)

The File object contains attributes of a single file. You can get an instance of a File object by calling the file method of a FileEntry object. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

FileReader FileReader is an object that allows one to read a file. Properties

readyState: One of the three states the reader can be in EMPTY, LOADING or DONE. result: The contents of the file that has been read. (DOMString) error: An object containing errors. (FileError) onloadstart: Called when the read starts. . (Function) onprogress: Called while reading the file, reports progress (progess.loaded/progress.total). (Function) -NOT SUPPORTED onload: Called when the read has successfully completed. (Function) onabort: Called when the read has been aborted. For instance, by invoking the abort() method. (Function) onerror: Called when the read has failed. (Function) onloadend: Called when the request has completed (either in success or failure). (Function)

Methods


Details

abort: Aborts reading file. readAsDataURL: Read file and return data as a base64 encoded data url. readAsText: Reads text file.

The FileReader object is a way to read files from the devices file system. Files can be read as text or as a base64 data encoded string. Users register their own event listners to receive the loadstart, progress, load, loadend, error and abort events. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Read As Data URL Parameters: - file - the file object to read Quick Example function win(file) {

var reader = new FileReader(); reader.onloadend = function(evt) { console.log("read success"); console.log(evt.target.result); }; reader.readAsDataURL(file); }; var fail = function(evt) { console.log(error.code); }; entry.file(win, fail);

Read As Text Parameters: file - the file object to read encoding - the encoding to use to encode the file's content. Default is UTF8.

Quick Example function win(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log("read success"); console.log(evt.target.result); }; reader.readAsText(file); }; var fail = function(evt) { console.log(error.code); }; entry.file(win, fail);

Abort Quick Example function win(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log("read success"); console.log(evt.target.result); }; reader.readAsText(file); reader.abort(); }; function fail(error) { console.log(error.code); } entry.file(win, fail);

Full Example <!DOCTYPE html> <html> <head> <title>FileReader Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // function onLoad() {

document.addEventListener("deviceready", onDeviceReady, false); } // PhoneGap is ready // function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); } function gotFS(fileSystem) { fileSystem.root.getFile("readme.txt", {create: true}, gotFileEntry, fail); } function gotFileEntry(fileEntry) { fileEntry.file(gotFile, fail); } function gotFile(file){ readDataUrl(file); readAsText(file); } function readDataUrl(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log("Read as data URL"); console.log(evt.target.result); }; reader.readAsDataURL(file); } function readAsText(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log("Read as text"); console.log(evt.target.result); }; reader.readAsText(file); } function fail(evt) { console.log(evt.target.error.code); } </script> </head> <body> <h1>Example</h1> <p>Read File</p> </body> </html>

iOS Quirks

encoding parameter is not supported, UTF8 encoding is always used.

FileWriter FileWriter is an object that allows one to write a file. Properties

readyState: One of the three states the reader can be in INIT, WRITING or DONE. fileName: The name of the file to be written. (DOMString)

length: The length of the file to be written. (long) position: The current position of the file pointer. (long) error: An object containing errors. (FileError) onwritestart: Called when the write starts. . (Function) onprogress: Called while writing the file, reports progress (progess.loaded/progress.total). (Function) -NOT SUPPORTED onwrite: Called when the request has completed successfully. (Function) onabort: Called when the write has been aborted. For instance, by invoking the abort() method. (Function) onerror: Called when the write has failed. (Function) onwriteend: Called when the request has completed (either in success or failure). (Function)

Methods


Details

abort: Aborts writing file. seek: Moves the file pointer to the byte specified. truncate: Shortens the file to the length specified. write: Writes data to the file.

The FileWriter object is a way to write files from the devices file system. Users register their own event listeners to receive the writestart, progress, write, writeend, error and abort events. A FileWriter is created for a single file. You can use it to write to a file multiple times. The FileWriter maintains the file's position and length attributes, so you can seek and write anywhere in the file. By default, the FileWriter writes to the beginning of the file (will overwrite existing data). Set the optional append boolean to true in the FileWriter's constructor to begin writing to the end of the file. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Seek Quick Example function win(writer) { // fast forwards file pointer to end of file writer.seek(writer.length); };

var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);

Truncate Quick Example function win(writer) { writer.truncate(10); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);

Write Quick Example function win(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.write("some sample text"); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);

Append Quick Example function win(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.seek(writer.length); writer.write("appended text"); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);

Abort Quick Example function win(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.write("some sample text"); writer.abort(); }; var fail = function(evt) { console.log(error.code); }; entry.createWriter(win, fail);

Full Example <!DOCTYPE html> <html> <head> <title>FileWriter Example</title>

<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); } function gotFS(fileSystem) { fileSystem.root.getFile("readme.txt", {create: true}, gotFileEntry, fail); } function gotFileEntry(fileEntry) { fileEntry.createWriter(gotFileWriter, fail); } function gotFileWriter(writer) { writer.onwrite = function(evt) { console.log("write success"); }; writer.write("some sample text"); // contents of file now 'some sample text' writer.truncate(11); // contents of file now 'some sample' writer.seek(4); // contents of file still 'some sample' but file pointer is after the 'e' in 'some' writer.write(" different text"); // contents of file now 'some different text' } function fail(error) { console.log(error.code); } </script> </head> <body> <h1>Example</h1> <p>Write File</p> </body> </html>

FileSystem This object represents a file system. Properties


Details

name: The name of the file system. (DOMString) root: The root directory of the file system. (DirectoryEntry)

The FileSystem object represents information about the file system. The name of the file system will be unique across the list of exposed file systems. The root property contains a DirectoryEntry object which represents the root directory of the file system.

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

File System Quick Example function onSuccess(fileSystem) { console.log(fileSystem.name); console.log(fileSystem.root.name); } // request the persistent file system window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);

Full Example <!DOCTYPE html> <html> <head> <title>File System Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail); } function onFileSystemSuccess(fileSystem) { console.log(fileSystem.name); console.log(fileSystem.root.name); } function fail(evt) { console.log(evt.target.error.code); } </script> </head> <body> <h1>Example</h1> <p>File System</p> </body> </html>

FileEntry This object represents a file on a file system. It is defined in the W3C Directories and Systems specification. Properties

isFile: Always true. (boolean) isDirectory: Always false. (boolean) name: The name of the FileEntry, excluding the path leading to it. (DOMString)

fullPath: The full absolute path from the root to the FileEntry. (DOMString)

NOTE: The following attributes are defined by the W3C specification, but are not supported by PhoneGap:

filesystem: The file system on which the FileEntry resides. (FileSystem)

Methods

getMetadata: Look up metadata about a file. moveTo: Move a file to a different location on the file system. copyTo: Copy a file to a different location on the file system. toURI: Return a URI that can be used to locate a file. remove: Delete a file. getParent: Look up the parent directory. createWriter: Creates a FileWriter object that can be used to write to a file. file: Creates a File object containing file properties.

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

getMetadata Look up metadata about a file. Parameters:

successCallback - A callback that is called with a Metadata object. (Function) errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileError object. (Function)

Quick Example function success(metadata) { console.log("Last Modified: " + metadata.modificationTime); } function fail(error) { alert(error.code); } // Request the metadata object for this entry entry.getMetadata(success, fail);

moveTo Move a file to a different location on the file system. It is an error to attempt to: move a file into its parent if a name different from its current one isn't provided; move a file to a path occupied by a directory;

In addition, an attempt to move a file on top of an existing file must attempt to delete and replace that file. Parameters:

parent - The parent directory to which to move the file. (DirectoryEntry) newName - The new name of the file. Defaults to the current name if unspecified. (DOMString) successCallback - A callback that is called with the FileEntry object of the new file. (Function) errorCallback - A callback that is called if an error occurs when attempting to move the file. Invoked with a FileError object. (Function)

Quick Example function success(entry) { console.log("New Path: " + entry.fullPath); } function fail(error) { alert(error.code); } function moveFile(entry) { var parent = document.getElementById('parent').value, parentEntry = new DirectoryEntry({fullPath: parent}); // move the file to a new directory and rename it entry.moveTo(parentEntry, "newFile.txt", success, fail); }

copyTo Copy a file to a new location on the file system. It is an error to attempt to: copy a file into its parent if a name different from its current one is not provided.

Parameters:

parent - The parent directory to which to copy the file. (DirectoryEntry) newName - The new name of the file. Defaults to the current name if unspecified. (DOMString) successCallback - A callback that is called with the FileEntry object of the new file. (Function) errorCallback - A callback that is called if an error occurs when attempting to copy the file. Invoked with a FileError object. (Function)

Quick Example function win(entry) {

console.log("New Path: " + entry.fullPath); } function fail(error) { alert(error.code); } function copyFile(entry) { var parent = document.getElementById('parent').value, parentEntry = new DirectoryEntry({fullPath: parent}); // copy the file to a new directory and rename it entry.copyTo(parentEntry, "file.copy", success, fail); }

toURI Returns a URI that can be used to locate the file. Quick Example // Request the metadata object for this entry var uri = entry.toURI(); console.log(uri);

remove Deletes a file. Parameters:

successCallback - A callback that is called after the file has been deleted. Invoked with no parameters. (Function) errorCallback - A callback that is called if an error occurs when attempting to delete the file. Invoked with a FileError object. (Function)

Quick Example function success(entry) { console.log("Removal succeeded"); } function fail(error) { alert('Error removing file: ' + error.code); } // remove the file entry.remove(success, fail);

getParent Look up the parent DirectoryEntry containing the file. Parameters:

successCallback - A callback that is called with the file's parent DirectoryEntry. (Function) errorCallback - A callback that is called if an error occurs when attempting to retrieve the parent DirectoryEntry. Invoked with a FileError object. (Function)

Quick Example function success(parent) { console.log("Parent Name: " + parent.name); } function fail(error) { alert(error.code); } // Get the parent DirectoryEntry entry.getParent(success, fail);

createWriter Create a FileWriter object associated with the file that the FileEntry represents. Parameters:

successCallback - A callback that is called with a FileWriter object. (Function) errorCallback - A callback that is called if an error occurs while attempting to create the FileWriter. Invoked with a FileError object. (Function)

Quick Example function success(writer) { writer.write("Some text to the file"); } function fail(error) { alert(error.code); } // create a FileWriter to write to the file entry.createWriter(success, fail);

file Return a File object that represents the current state of the file that this FileEntry represents. Parameters:

successCallback - A callback that is called with a File object. (Function) errorCallback - A callback that is called if an error occurs when creating the File object (e.g. the underlying file no longer exists). Invoked with a FileError object. (Function)

Quick Example function success(file) { console.log("File size: " + file.size); } function fail(error) { alert("Unable to retrieve file properties: " + error.code); } // obtain properties of a file entry.file(success, fail);

DirectoryEntry This object represents a directory on a file system. It is defined in the W3C Directories and Systems specification. Properties

isFile: Always false. (boolean) isDirectory: Always true. (boolean) name: The name of the DirectoryEntry, excluding the path leading to it. (DOMString) fullPath: The full absolute path from the root to the DirectoryEntry. (DOMString)

NOTE: The following attributes are defined by the W3C specification, but are not supported by PhoneGap:

filesystem: The file system on which the DirectoryEntry resides. (FileSystem)

Methods The following methods can be invoked on a DirectoryEntry object:

getMetadata: Look up metadata about a directory. moveTo: Move a directory to a different location on the file system. copyTo: Copy a directory to a different location on the file system. toURI: Return a URI that can be used to locate a directory. remove: Delete a directory. The directory must be empty. getParent: Look up the parent directory. createReader: Create a new DirectoryReader that can read entries from a directory. getDirectory: Create or look up a directory. getFile: Create or look up a file. removeRecursively: Delete a directory and all of its contents.

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

getMetadata Look up metadata about a directory.

Parameters:

successCallback - A callback that is called with a Metadata object. (Function) errorCallback - A callback that is called if an error occurs retrieving the Metadata. Invoked with a FileError object. (Function)

Quick Example function success(metadata) { console.log("Last Modified: " + metadata.modificationTime); } function fail(error) { alert(error.code); } // Request the metadata object for this entry entry.getMetadata(success, fail);

moveTo Move a directory to a different location on the file system. It is an error to attempt to: move a directory inside itself or to any child at any depth; move a directory into its parent if a name different from its current one is not provided; move a directory to a path occupied by a file; move a directory to a path occupied by a directory which is not empty.

In addition, an attempt to move a directory on top of an existing empty directory must attempt to delete and replace that directory. Parameters:

parent - The parent directory to which to move the directory. (DirectoryEntry) newName - The new name of the directory. Defaults to the current name if unspecified. (DOMString) successCallback - A callback that is called with the DirectoryEntry object of the new directory. (Function) errorCallback - A callback that is called if an error occurs when attempting to move the directory. Invoked with a FileError object. (Function)

Quick Example function success(entry) { console.log("New Path: " + entry.fullPath); } function fail(error) { alert(error.code); } function moveDir(entry) { var parent = document.getElementById('parent').value, newName = document.getElementById('newName').value, parentEntry = new DirectoryEntry({fullPath: parent}); // move the directory to a new directory and rename it entry.moveTo(parentEntry, newName, success, fail); }

copyTo Copy a directory to a different location on the file system. It is an error to attempt to: copy a directory inside itself at any depth; copy a directory into its parent if a name different from its current one is not provided.

Directory copies are always recursive - that is, they copy all contents of the directory. Parameters:

parent - The parent directory to which to copy the directory. (DirectoryEntry) newName - The new name of the directory. Defaults to the current name if unspecified. (DOMString) successCallback - A callback that is called with the DirectoryEntry object of the new directory. (Function) errorCallback - A callback that is called if an error occurs when attempting to copy the underlying directory. Invoked with a FileError object. (Function)

Quick Example function win(entry) { console.log("New Path: " + entry.fullPath); } function fail(error) { alert(error.code); } function copyDir(entry) { var parent = document.getElementById('parent').value, newName = document.getElementById('newName').value, parentEntry = new DirectoryEntry({fullPath: parent}); // copy the directory to a new directory and rename it entry.copyTo(parentEntry, newName, success, fail); }

toURI Returns a URI that can be used to locate the directory. Quick Example // Get the URI for this directory var uri = entry.toURI(); console.log(uri);

remove Deletes a directory. It is an error to attempt to: delete a directory that is not empty; delete the root directory of a filesystem.

Parameters:

successCallback - A callback that is called after the directory has been deleted. Invoked with no parameters. (Function) errorCallback - A callback that is called if an error occurs when attempting to delete the directory. Invoked with a FileError object. (Function)

Quick Example function success(entry) { console.log("Removal succeeded"); } function fail(error) { alert('Error removing directory: ' + error.code); } // remove this directory entry.remove(success, fail);

getParent Look up the parent DirectoryEntry containing the directory. Parameters:

successCallback - A callback that is called with the directory's parent DirectoryEntry. (Function) errorCallback - A callback that is called if an error occurs when attempting to retrieve the parent DirectoryEntry. Invoked with a FileError object. (Function)

Quick Example function success(parent) { console.log("Parent Name: " + parent.name); } function fail(error) { alert('Failed to get parent directory: ' + error.code); } // Get the parent DirectoryEntry entry.getParent(success, fail);

createReader Creates a new DirectoryReader to read entries in a directory. Quick Example // create a directory reader var directoryReader = entry.createReader();

getDirectory Creates or looks up an existing directory. It is an error to attempt to: create a directory whose immediate parent does not yet exist.

Parameters:

path - The path to the directory to be looked up or created. Either an absolute path, or a relative path from this DirectoryEntry. (DOMString) options - Options to specify whether the directory is created if it doesn't exist. (Flags) successCallback - A callback that is invoked with a DirectoryEntry object. (Function) errorCallback - A callback that is called if an error occurs creating or looking up the directory. Invoked with a FileError object. (Function)

Quick Example function success(parent) { console.log("Parent Name: " + parent.name); } function fail(error) { alert("Unable to create new directory: " + error.code); } // Retrieve an existing directory, or create it if it does not already exist entry.getDirectory("newDir", {create: true, exclusive: false}, success, fail);

getFile Creates or looks up a file. It is an error to attempt to: create a file whose immediate parent does not yet exist.

Parameters:

path - The path to the file to be looked up or created. Either an absolute path, or a relative path from this DirectoryEntry. (DOMString) options - Options to specify whether the file is created if it doesn't exist. (Flags) successCallback - A callback that is invoked with a FileEntry object. (Function) errorCallback - A callback that is called if an error occurs creating or looking up the file. Invoked with a FileError object. (Function)

Quick Example function success(parent) { console.log("Parent Name: " + parent.name); } function fail(error) { alert("Failed to retrieve file: " + error.code); } // Retrieve an existing file, or create it if it does not exist entry.getFile("newFile.txt", {create: true, exclusive: false}, success, fail);

removeRecursively Deletes a directory and all of its contents. In the event of an error (e.g. trying to delete a directory that contains a file that cannot be removed), some of the contents of the directory may be deleted. It is an error to attempt to: delete the root directory of a filesystem.

Parameters:

successCallback - A callback that is called after the DirectoryEntry has been deleted. Invoked with no parameters. (Function) errorCallback - A callback that is called if an error occurs when attempting to delete the DirectoryEntry. Invoked with a FileError object. (Function)

Quick Example function success(parent) { console.log("Remove Recursively Succeeded"); } function fail(error) { alert("Failed to remove directory or it's contents: " + error.code); } // remove the directory and all it's contents entry.removeRecursively(success, fail);

DirectoryReader An object that lists files and directories in a directory. Defined in the Directories and Systems specification. Methods

readEntries: Read the entries in a directory.

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

readEntries Read the entries in this directory. Parameters:

successCallback - A callback that is passed an array of FileEntry and DirectoryEntry objects. (Function) errorCallback - A callback that is called if an error occurs retrieving the directory listing. Invoked with a FileError object. (Function)

Quick Example function success(entries) { var i; for (i=0; i<entries.length; i++) { console.log(entries[i].name); } } function fail(error) { alert("Failed to list directory contents: " + error.code); } // Get a directory reader var directoryReader = dirEntry.createReader(); // Get a list of all the entries in the directory directoryReader.readEntries(success,fail);

FileTransfer FileTransfer is an object that allows you to upload files to a server. Properties N/A Methods

Details

upload: sends a file to a server.

The FileTransfer object provides a way to upload files to a remote server using an HTTP multi-part POST request. Both HTTP and HTTPS protocols are supported. Optional parameters can be specified by passing a FileUploadOptions object to the upload method. On successful upload, the success callback will be called with a FileUploadResult object. If an error occurs, the error callback will be invoked with a FileTransferError object. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // !! Assumes variable fileURI contains a valid URI to a text file on the device 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); } var options = new FileUploadOptions(); options.fileKey="file"; options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1); options.mimeType="text/plain";

var params = new Object(); params.value1 = "test"; params.value2 = "param"; options.params = params; var ft = new FileTransfer(); ft.upload(fileURI, "http://some.server.com/upload.php", win, fail, options);

Full Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>File Transfer Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.min.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { // Retrieve image file location from specified source navigator.camera.getPicture(uploadPhoto, function(message) { alert('get picture failed'); }, { quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY } ); } function uploadPhoto(imageURI) { var options = new FileUploadOptions(); options.fileKey="file"; options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1); options.mimeType="image/jpeg"; var params = new Object(); params.value1 = "test"; params.value2 = "param"; options.params = params; var ft = new FileTransfer(); ft.upload(imageURI, "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); } </script> </head> <body> <h1>Example</h1> <p>Upload File</p> </body> </html>

FileUploadOptions A FileUploadOptions object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.

Properties

fileKey: The name of the form element. If not set defaults to "file". (DOMString) fileName: The file name you want the file to be saved as on the server. If not set defaults to "image.jpg". (DOMString) mimeType: The mime type of the data you are uploading. If not set defaults to "image/jpeg". (DOMString) params: A set of optional key/value pairs to be passed along in the HTTP request. (Object)

Description A FileUploadOptions object can be passed to the FileTransfer objects upload method in order to specify additional parameters to the upload script.

FileUploadResult A FileUploadResult object is returned via the success callback of the FileTransfer upload method. Properties

bytesSent: The number of bytes sent to the server as part of the upload. (long) responseCode: The HTTP response code returned by the server. (long) response: The HTTP response returned by the server. (DOMString)

Description The FileUploadResult object is returned via the success callback of the FileTransfer upload method. iOS Quirks iOS does not include values for responseCode nor bytesSent in the success callback FileUploadResult object.

Flags This object is used to supply arguments to the DirectoryEntry getFile and getDirectory methods, which look up or create files and directories, respectively. Properties

create: Used to indicate that the file or directory should be created, if it does not exist. If not set defaults to false. (boolean)

exclusive: By itself, exclusive has no effect. Used with create, it causes the file or directory creation to fail if the target path already exists. If not set defaults to false. (boolean) Supported Platforms

Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Quick Example // Get the data directory, creating it if it doesn't exist. dataDir = fileSystem.root.getDirectory("data", {create: true}); // Create the lock file, if and only if it doesn't exist. lockFile = dataDir.getFile("lockfile.txt", {create: true, exclusive: true});

LocalFileSystem This object provides a way to obtain root file systems. Methods

requestFileSystem: Requests a filesystem. (Function) resolveLocalFileSystemURI: Retrieve a DirectoryEntry or FileEntry using local URI. (Function)

Constants


Details

LocalFileSystem.PERSISTENT: Used for storage that should not be removed by the user agent without application or user permission. LocalFileSystem.TEMPORARY: Used for storage with no guarantee of persistence.

The LocalFileSystem object methods are defined on the window object. Supported Platforms Android BlackBerry WebWorks (OS 5.0 and higher) iOS

Request File System Quick Example function onSuccess(fileSystem) { console.log(fileSystem.name); } // request the persistent file system

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError);

Resolve Local File System URI Quick Example function onSuccess(fileEntry) { console.log(fileEntry.name); } window.resolveLocalFileSystemURI("file:///example.txt", onSuccess, onError);

Full Example <!DOCTYPE html> <html> <head> <title>Local File System Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail); window.resolveLocalFileSystemURI("file:///example.txt", onResolveSuccess, fail); } function onFileSystemSuccess(fileSystem) { console.log(fileSystem.name); } function onResolveSuccess(fileEntry) { console.log(fileEntry.name); } function fail(evt) { console.log(evt.target.error.code); } </script> </head> <body> <h1>Example</h1> <p>Local File System</p> </body> </html>

Metadata This interface supplies information about the state of a file or directory. Properties

Details

modificationTime: This is the time at which the file or directory was last modified. (Date)

The Metadata object represents information about the state of a file or directory. You can get an instance of a Metadata object by calling the getMetadata method of a DirectoryEntry or FileEntry object.

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

Quick Example function win(metadata) { console.log("Last Modified: " + metadata.modificationTime); } // Request the metadata object for this entry entry.getMetadata(win, null);

FileError A 'FileError' object is set when an error occurs in any of the File API methods. Properties

code: One of the predefined error codes listed below.

Constants

FileError.NOT_FOUND_ERR FileError.SECURITY_ERR FileError.ABORT_ERR FileError.NOT_READABLE_ERR FileError.ENCODING_ERR FileError.NO_MODIFICATION_ALLOWED_ERR FileError.INVALID_STATE_ERR FileError.SYNTAX_ERR FileError.INVALID_MODIFICATION_ERR FileError.QUOTA_EXCEEDED_ERR FileError.TYPE_MISMATCH_ERR FileError.PATH_EXISTS_ERR

Description The FileError object is the only parameter of any of the File API's error callbacks. Developers must read the code property to determine the type of error.

FileTransferError A FileTransferError object is returned via the error callback when an error occurs. Properties

code: One of the predefined error codes listed below. (int)

Constants

FileTransferError.FILE_NOT_FOUND_ERR FileTransferError.INVALID_URL_ERR FileTransferError.CONNECTION_ERR

Description The FileTransferError object is returned via the error callback when an error occurs when uploading a file.

Geolocation The geolocation object provides access to the device's GPS sensor. Geolocation provides location information for the device, 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. No guarantee is given that the API returns the device's actual location. This API is based on the W3C Geo location 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 geolocation support, PhoneGap's implementation should be compatible with the W3C specification. Methods geolocation.getCurrentPosition geolocation.watchPosition geolocation.clearWatch

Arguments geolocationSuccess geolocationError geolocationOptions

Objects (Read-Only) Position PositionError Coordinates

geolocation.getCurrentPosition Returns the device's current position as a Position object. navigator.geolocation.getCurrentPosition(geolocationSuccess, [geolocationError], [geolocationOptions]);

Parameters

geolocationSuccess: The callback that is called with the current position. geolocationError: (Optional) The callback that is called if there was an error. geolocationOptions: (Optional) The geolocation options.

Description Function geolocation.getCurrentPositon is an asynchronous function. It 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 invoked with a PositionError object. Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // onSuccess Callback // This method accepts a `Position` object, which contains // the current GPS coordinates // var onSuccess = function(position) { alert('Latitude: ' + position.coords.latitude + '\n' + 'Longitude: ' + position.coords.longitude + '\n' + 'Altitude: ' + position.coords.altitude + '\n' + 'Accuracy: ' + position.coords.accuracy + '\n' + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' + 'Heading: ' + position.coords.heading + '\n' + 'Speed: ' + position.coords.speed + '\n' + 'Timestamp: ' + new Date(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);

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { navigator.geolocation.getCurrentPosition(onSuccess, onError); } // onSuccess Geolocation // function onSuccess(position) { var element = document.getElementById('geolocation'); element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + 'Altitude: ' + position.coords.altitude + '<br />' + 'Accuracy: ' + position.coords.accuracy + '<br />' + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' + 'Heading: ' + position.coords.heading + '<br />' + 'Speed: ' + position.coords.speed + '<br />' + 'Timestamp: ' + new Date(position.timestamp) + '<br />'; } // onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } </script> </head> <body> <p id="geolocation">Finding geolocation...</p> </body> </html>

geolocation.watchPosition Watches for changes to the device's current position. var watchId = navigator.geolocation.watchPosition(geolocationSuccess, [geolocationError], [geolocationOptions]);

Parameters

geolocationSuccess: The callback that is called with the current position.


Returns

geolocationError: (Optional) The callback that is called if there was an error. geolocationOptions: (Optional) The geolocation options.

String: returns a watch id that references the watch position interval. The watch id can be used with geolocation.clearWatch to stop watching for changes in position.

Description Function geolocation.watchPosition is an asynchronous function. It returns the device's current position when a change in position has been detected. When the device has retrieved a new location, the geolocationSuccess callback is invoked with a Position object as the parameter. If there is an error, the geolocationError callback is invoked with a PositionError object. Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // onSuccess Callback // This method accepts a `Position` object, which contains // the current GPS coordinates // function onSuccess(position) { var element = document.getElementById('geolocation'); element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + '<hr />' + element.innerHTML; } // onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } // Options: retrieve the location every 3 seconds // var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 });

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); var watchID = null;

// PhoneGap is ready // function onDeviceReady() { // Update every 3 seconds var options = { frequency: 3000 }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); } // onSuccess Geolocation // 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'); } </script> </head> <body> <p id="geolocation">Watching geolocation...</p> </body> </html>

geolocation.clearWatch Stop watching for changes to the device's location referenced by the watchID parameter. navigator.geolocation.clearWatch(watchID);

Parameters

watchID: The id of the watchPosition interval to clear. (String)

Description Function geolocation.clearWatch stops watching changes to the device's location by clearing the geolocation.watchPosition referenced by watchID. Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // Options: retrieve the location every 3 seconds // var watchID = navigator.geolocation.watchPosition(onSuccess, onError, { frequency: 3000 }); // ...later on... navigator.geolocation.clearWatch(watchID);

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); var watchID = null; // PhoneGap is ready // function onDeviceReady() { // Update every 3 seconds var options = { frequency: 3000 }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); } // onSuccess Geolocation // function onSuccess(position) { var element = document.getElementById('geolocation'); element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + '<hr />' + element.innerHTML; } // clear the watch that was started earlier // function clearWatch() { if (watchID != null) { navigator.geolocation.clearWatch(watchID); watchID = null; } } // onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } </script> </head> <body> <p id="geolocation">Watching geolocation...</p> <button onclick="clearWatch();">Clear Watch</button> </body> </html>

Coordinates A set of properties that describe the geographic coordinates of a position. Properties

latitude: Latitude in decimal degrees. (Number) longitude: Longitude in decimal degrees. (Number) altitude: Height of the position in meters above the ellipsoid. (Number)

accuracy: Accuracy level of the latitude and longitude coordinates in meters. (Number) altitudeAccuracy: Accuracy level of the altitude coordinate in meters. (Number) heading: Direction of travel, specified in degrees counting clockwise relative to the true north. (Number) speed: Current ground speed of the device, specified in meters per second. (Number)

Description The Coordinates object is created and populated by PhoneGap, and attached to the Position object. The Position object is then returned to the user through a callback function. Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // onSuccess Callback // 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: ' + new Date(position.timestamp) + '\n'); }; // onError Callback // var onError = function() { alert('onError!'); }; navigator.geolocation.getCurrentPosition(onSuccess, onError);

Full Example <!DOCTYPE html> <html> <head> <title>Geolocation Position Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Set an event to wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is loaded and Ready // function onDeviceReady() { navigator.geolocation.getCurrentPosition(onSuccess, onError); } // Display `Position` properties from the geolocation

// function onSuccess(position) { var div = document.getElementById('myDiv'); div.innerHTML = 'Latitude: ' + position.coords.latitude + '<br/>' + 'Longitude: ' + position.coords.longitude + '<br/>' + 'Altitude: ' + position.coords.altitude + '<br/>' + 'Accuracy: ' + position.coords.accuracy + '<br/>' + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br/>' + 'Heading: ' + position.coords.heading + '<br/>' + 'Speed: ' + position.coords.speed + '<br/>'; } // Show an alert if there is a problem getting the geolocation // function onError() { alert('onError!'); } </script> </head> <body> <div id="myDiv"></div> </body> </html>

Android Quirks altitudeAccuracy: This property is not support by Android devices, it will always return null.

Position Contains Position coordinates that are created by the geolocation API. Properties

coords: A set of geographic coordinates. (Coordinates) timestamp: Creation timestamp for coords in milliseconds. (DOMTimeStamp)

Description The Position object is created and populated by PhoneGap, and returned to the user through a callback function. Supported Platforms Android BlackBerry (OS 4.6) BlackBerry WebWorks (OS 5.0 and higher) iPhone

Quick Example // onSuccess Callback // var onSuccess = function(position) { alert('Latitude: ' + position.coords.latitude 'Longitude: ' + position.coords.longitude

+ '\n' + + '\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: ' + new Date(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);

Full Example <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { navigator.geolocation.getCurrentPosition(onSuccess, onError); } // onSuccess Geolocation // function onSuccess(position) { var element = document.getElementById('geolocation'); element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + 'Altitude: ' + position.coords.altitude + '<br />' + 'Accuracy: ' + position.coords.accuracy + '<br />' + 'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '<br />' + 'Heading: ' + position.coords.heading + '<br />' + 'Speed: ' + position.coords.speed + '<br />' + 'Timestamp: ' + new Date(position.timestamp) + '<br />'; } // onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } </script> </head> <body> <p id="geolocation">Finding geolocation...</p> </body> </html>

iPhone Quirks

timestamp: Uses seconds instead of milliseconds.

A workaround is to manually convert the timestamp to milliseconds (x 1000): var onSuccess = function(position) {

alert('Latitude: ' + position.coords.latitude + '\n' + 'Longitude: ' + position.coords.longitude + '\n' + 'Timestamp: ' + new Date(position.timestamp * 1000) + '\n'); };

PositionError A PositionError object is returned to the geolocationError callback when an error occurs. Properties

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

Constants

PositionError.PERMISSION_DENIED PositionError.POSITION_UNAVAILABLE PositionError.TIMEOUT

Description The PositionError object is returned to the user through the geolocationError callback function when an error occurs with geolocation.

geolocationSuccess The user's callback function that is called when a geolocation position is available. function(position) { // Do something }

Parameters

position: The geolocation position returned by the device. (Position)

Example function geolocationSuccess(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: ' + new Date(position.timestamp) + '\n');

geolocationError The user's callback function that is called when there is an error for geolocation functions. function(error) { // Handle the error }

Parameters

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

geolocationOptions Optional parameters to customize the retrieval of the geolocation. { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true };

Options

frequency: How often to retrieve the position in milliseconds. This option is not part of the W3C spec and will be removed in the future. maximumAge should be used instead. (Number) (Default: 10000) enableHighAccuracy: Provides a hint that the application would like to receive the best possible results. (Boolean) timeout: The maximum length of time (msec) that is allowed to pass from the call to geolocation.getCurrentPosition or geolocation.watchPosition until the corresponding geolocationSuccess callback is invoked. (Number)

maximumAge: Accept a cached position whose age is no greater than the specified time in milliseconds. (Number)

Android Quirks The Android 2.x simulators will not return a geolocation result unless the enableHighAccuracy option is set to true. { enableHighAccuracy: true }

Media The Media object provides the ability to record and play back audio files on a device. var media = new Media(src, mediaSuccess, [mediaError], [mediaStatus]);

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. Parameters

src: A URI containing the audio content. (DOMString) mediaSuccess: (Optional) The callback that is invoked after a Media object has completed the current play/record or stop action. (Function) mediaError: (Optional) The callback that is invoked if there was an error. (Function) mediaStatus: (Optional) The callback that is invoked to indicate status changes. (Function)

Methods media.getCurrentPosition: Returns the current position within an audio file. media.getDuration: Returns the duration of an audio file. media.play: Start or resume playing audio file. media.pause: Pause playing audio file. media.release: Releases the underlying OS'es audio resources. media.seekTo: Moves the position within the audio file. media.startRecord: Start recording audio file. media.stopRecord: Stop recording audio file. media.stop: Stop playing audio file.

Additional ReadOnly Parameters

_position: The position within the audio playback in seconds. Not automatically updated during play, call getCurrentPosition to update. _duration: The duration of the media in seconds.

Supported Platforms Android iOS

media.getCurrentPosition Returns the current position within an audio file. media.getCurrentPosition(mediaSuccess, [mediaError]);

Parameters

mediaSuccess: The callback that is called with the current position in seconds.

mediaError: (Optional) The callback that is called if there was an error.

Description Function media.getCurrentPosition is an asynchronous function that returns the current position of the underlying audio file of a Media object. Also updates the _position parameter within the Media object. Supported Platforms Android iOS

Quick Example // Audio player // var my_media = new Media(src, onSuccess, onError); // Update media position every second var mediaTimer = setInterval(function() { // get media position my_media.getCurrentPosition( // success callback function(position) { if (position > -1) { console.log((position) + " sec"); } }, // error callback function(e) { console.log("Error getting pos=" + e); } ); }, 1000);

Full Example <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s__rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body> </html>

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 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s__rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body> </html>

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 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s__rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body> </html>

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 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s__rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body>

</html>

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 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s__rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <p id="media">Recording audio...</p> <p id="audio_position"></p> </body> </html>

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 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Media Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <a href="#" class="btn large" onclick="playAudio('http://audio.ibeat.org/content/p1rj1s/p1rj1s__rockGuitar.mp3');">Play Audio</a> <a href="#" class="btn large" onclick="pauseAudio();">Pause Playing Audio</a> <a href="#" class="btn large" onclick="stopAudio();">Stop Playing Audio</a> <p id="audio_position"></p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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; } </script> </head> <body> <p id="media">Recording audio...</p> <p id="audio_position"></p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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 ); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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 ); } </script> </head> <body> <p><a href="#" onclick="showConfirm(); return false;">Show Confirm</a></p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body>

</html>

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 <!DOCTYPE html> <html> <head> <title>Notification Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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); } </script> </head> <body> <p><a href="#" onclick="showAlert(); return false;">Show Alert</a></p> <p><a href="#" onclick="playBeep(); return false;">Play Beep</a></p> <p><a href="#" onclick="vibrate(); return false;">Vibrate</a></p> </body> </html>

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 <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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); } </script> </head> <body> <h1>Example</h1> <p>Open Database</p> </body>

</html>

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 <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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 processing SQL: "+err); } // Transaction success callback // function successCB() { alert("success!"); } </script> </head> <body> <h1>Example</h1> <p>Database</p> </body> </html>

Android 1.X Quirks

changeVersion: This method is not support by Android 1.X devices.

SQLTransaction Contains methods that allow the user to execute SQL statements against the Database. Methods

Details

executeSql: executes a SQL statement

When you call a Database objects transaction method it's callback methods will be called with a SQLTransaction object. The user can build up a database transaction by calling the executeSql method multiple times. Supported Platforms Android BlackBerry WebWorks (OS 6.0 and higher) iPhone

Execute SQL 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); } function successCB() { alert("success!"); } var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(populateDB, errorCB, successCB);

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // 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(err) { alert("Error processing SQL: "+err); } // Transaction success callback // function successCB() { alert("success!"); } </script> </head> <body> <h1>Example</h1> <p>SQLTransaction</p> </body> </html>

SQLResultSet When the executeSql method of a SQLTransaction is called it will invoke it's callback with a SQLResultSet. Properties


Details

insertId: the row ID of the row that the SQLResultSet object's SQL statement inserted into the database rowAffected: the number of rows that were changed by the SQL statement. If the statement did not affect any rows then it is set to 0. rows: a SQLResultSetRowList representing the rows returned. If no rows are returned the object will be empty.

When you call the SQLTransaction executeSql method it's callback methods will be called with a SQLResultSet object. The result object has three properties. The first is the insertId which will return the row number of a success SQL insert statement. If the SQL statement is not an insert then the insertId is not set. The rowAffected is always 0 for a SQL select statement. For insert or update statements it returns the number of rows that have been modified. The final property is of type SQLResultSetList and it contains the data returned from a SQL select statement. Supported Platforms Android BlackBerry WebWorks (OS 6.0 and higher) iPhone

Execute SQL Quick Example function queryDB(tx) { tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB); } function querySuccess(tx, results) { // this will be empty since no rows were inserted. console.log("Insert ID = " + results.insertId); // this will be 0 since it is a select statement console.log("Rows Affected = " + results.rowAffected); // the number of rows returned by the select statement console.log("Insert ID = " + results.rows.length); } function errorCB(err) { alert("Error processing SQL: "+err.code); } var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(queryDB, errorCB);

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // 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")'); } // Query the database // function queryDB(tx) { tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB); } // Query the success callback // function querySuccess(tx, results) { // this will be empty since no rows were inserted. console.log("Insert ID = " + results.insertId); // this will be 0 since it is a select statement console.log("Rows Affected = " + results.rowAffected); // the number of rows returned by the select statement console.log("Insert ID = " + results.rows.length); } // Transaction error callback // function errorCB(err) { console.log("Error processing SQL: "+err.code); } // Transaction success callback // function successCB() { var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(queryDB, errorCB); } // PhoneGap is ready // function onDeviceReady() {

var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(populateDB, errorCB, successCB); } </script> </head> <body> <h1>Example</h1> <p>Database</p> </body> </html>

SQLResultSetList One of the properties of the SQLResultSet containing the rows returned from a SQL query. Properties

length: the number of rows returned by the SQL query

Methods

Details

item: returns the row at the specified index represented by a JavaScript object.

The SQLResultSetList contains the data returned from a SQL select statement. The object contains a length property letting you know how many rows the select statement has been returned. To get a row of data you would call the item method specifing an index. The item method returns a JavaScript Object who's properties are the columns of the database the select statement was executed against. Supported Platforms Android BlackBerry WebWorks (OS 6.0 and higher) iPhone

Execute SQL Quick Example function queryDB(tx) { tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB); } function querySuccess(tx, results) { var len = results.rows.length; console.log("DEMO table: " + len + " rows found."); for (var i=0; i<len; i++){ console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data); } } function errorCB(err) { alert("Error processing SQL: "+err.code); } var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(queryDB, errorCB);

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // 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")'); } // Query the database // function queryDB(tx) { tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB); } // Query the success callback // function querySuccess(tx, results) { var len = results.rows.length; console.log("DEMO table: " + len + " rows found."); for (var i=0; i<len; i++){ console.log("Row = " + i + " ID = " + results.rows.item(i).id + " Data = " + results.rows.item(i).data); } } // Transaction error callback // function errorCB(err) { console.log("Error processing SQL: "+err.code); } // Transaction success callback // function successCB() { var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(queryDB, errorCB); } // PhoneGap is ready // function onDeviceReady() { var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(populateDB, errorCB, successCB); } </script> </head> <body> <h1>Example</h1> <p>Database</p> </body> </html>

SQLError A SQLError object is thrown when an error occurs.

Properties

code: One of the predefined error codes listed below. message: A description of the error.

Constants

SQLError.UNKNOWN_ERR SQLError.DATABASE_ERR SQLError.VERSION_ERR SQLError.TOO_LARGE_ERR SQLError.QUOTA_ERR SQLError.SYNTAX_ERR SQLError.CONSTRAINT_ERR SQLError.TIMEOUT_ERR

Description The SQLError object is thrown when an error occurs when manipulating a database. localStorage Provides access to a W3C Storage interface (http://dev.w3.org/html5/webstorage/#the-localstorage-attribute) var storage = window.localStorage;

Methods


Details

key: Returns the name of the key at the position specified. getItem: Returns the item identified by it's key. setItem: Saves and item at the key provided. removeItem: Removes the item identified by it's key. clear: Removes all of the key value pairs.

localStorage provides an interface to a W3C Storage interface. It allows one to save data as key-value pairs.

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

Key Quick Example var keyName = window.localStorage.key(0);

Set Item Quick Example window.localStorage.setItem("key", "value");

Get Item Quick Example var value = window.localStorage.getItem("key"); // value is now equal to "value"

Remove Item Quick Example window.localStorage.removeItem("key");

Clear Quick Example window.localStorage.clear();

Full Example <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { window.localStorage.setItem("key", "value"); var keyname = window.localStorage.key(i); // keyname is now equal to "key" var value = window.localStorage.getItem("key"); // value is now equal to "value" window.localStorage.removeItem("key"); window.localStorage.setItem("key2", "value2"); window.localStorage.clear(); // localStorage is now empty } </script> </head> <body> <h1>Example</h1> <p>localStorage</p> </body> </html>

You might also like