Events

There are various events provided by cordova to be used by the application. The application code could add listeners for these events. For example:

HTML File

<!DOCTYPE html>
<html>
    <head>
    <title>Device Ready Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8" src="example.js"></script>
    </head>
    <body onload="onLoad()">
    </body>
</html>

JS File

// example.js file
// Wait for device API libraries to load
//
function onLoad() {
    document.addEventListener("deviceready", onDeviceReady, false);
}

// device APIs are available
//
function onDeviceReady() {
    document.addEventListener("pause", onPause, false);
    document.addEventListener("resume", onResume, false);
    document.addEventListener("menubutton", onMenuKeyDown, false);
    // Add similar listeners for other events
}

function onPause() {
    // Handle the pause event
}

function onResume() {
    // Handle the resume event
}

function onMenuKeyDown() {
    // Handle the menubutton event
}

// Add similar event handlers for other events

Note: Applications typically should use document.addEventListener to attach an event listener once the deviceready

The following table lists the cordova events and the supported platforms:

Supported Platforms/
Events
android ios Windows
deviceready
pause
resume
backbutton
menubutton
searchbutton
startcallbutton
endcallbutton
volumedownbutton
volumeupbutton
activated

deviceready

The deviceready event fires when Cordova is fully loaded. This event is essential to any application. It signals that Cordova's device APIs have loaded and are ready to access.

Cordova consists of two code bases: native and JavaScript. While the native code loads, a custom loading image displays. However, JavaScript only loads once the DOM loads. This means the web app may potentially call a Cordova JavaScript function before the corresponding native code becomes available.

The deviceready event fires once Cordova has fully loaded. Once the event fires, you can safely make calls to Cordova APIs. Applications typically attach an event listener with document.addEventListener once the HTML document's DOM has loaded.

The deviceready event behaves somewhat differently from others. Any event handler registered after the deviceready event fires has its callback function called immediately.

Quick Example

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    // Now safe to use device APIs
}

pause

The pause event fires when the native platform puts the application into the background, typically when the user switches to a different application.

Quick Example

document.addEventListener("pause", onPause, false);

function onPause() {
    // Handle the pause event
}

iOS Quirks

In the pause handler, any calls to the Cordova API or to native plugins that go through Objective-C do not work, along with any interactive calls, such as alerts or console.log(). They are only processed when the app resumes, on the next run loop.

The iOS-specific resign event is available as an alternative to pause, and detects when users enable the Lock button to lock the device with the app running in the foreground. If the app (and device) is enabled for multi-tasking, this is paired with a subsequent pause event, but only under iOS 5. In effect, all locked apps in iOS 5 that have multi-tasking enabled are pushed to the background. For apps to remain running when locked under iOS 5, disable the app's multi-tasking by setting UIApplicationExitsOnSuspend to YES. To run when locked on iOS 4, this setting does not matter.

resume

The resume event fires when the native platform pulls the application out from the background.

Quick Example

document.addEventListener("resume", onResume, false);

function onResume() {
    // Handle the resume event
}

iOS Quirks

Any interactive functions called from a pause event handler execute later when the app resumes, as signaled by the resume event. These include alerts, console.log(), and any calls from plugins or the Cordova API, which go through Objective-C.

  • active event

    The iOS-specific active event is available as an alternative to resume, and detects when users disable the Lock button to unlock the device with the app running in the foreground. If the app (and device) is enabled for multi-tasking, this is paired with a subsequent resume event, but only under iOS 5. In effect, all locked apps in iOS 5 that have multi-tasking enabled are pushed to the background. For apps to remain running when locked under iOS 5, disable the app's multi-tasking by setting UIApplicationExitsOnSuspend to YES. To run when locked on iOS 4, this setting does not matter.

  • resume event

    When called from a resume event handler, interactive functions such as alert() need to be wrapped in a setTimeout() call with a timeout value of zero, or else the app hangs. For example:

    document.addEventListener("resume", onResume, false);
    function onResume() {
        setTimeout(function() {
                // TODO: do your thing!
            }, 0);
    }
    

Android Quirks

Refer Android Life Cycle Guide for details on android quirks with the resume event.

backbutton

The event fires when the user presses the back button. To override the default back-button behavior, register an event listener for the backbutton event. It is no longer necessary to call any other method to override the back-button behavior.

Quick Example

document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown() {
    // Handle the back button
}

Windows Quirks

Throw an error in a backbutton callback to force the default behavior, which is an app exit:

document.addEventListener('backbutton', function (evt) {
    if (cordova.platformId !== 'windows') {
        return;
    }

    if (window.location.href !== firstPageUrl) {
        window.history.back();
    } else {
        throw new Error('Exit'); // This will suspend the app
    }
}, false);

menubutton

The event fires when the user presses the menu button. Applying an event handler overrides the default menu button behavior.

Quick Example

document.addEventListener("menubutton", onMenuKeyDown, false);

function onMenuKeyDown() {
    // Handle the back button
}

searchbutton

The event fires when the user presses the search button on Android. If you need to override the default search button behavior on Android you can register an event listener for the 'searchbutton' event.

Quick Example

document.addEventListener("searchbutton", onSearchKeyDown, false);

function onSearchKeyDown() {
    // Handle the search button
}

startcallbutton

The event fires when the user presses the start call button. If you need to override the default start call behavior you can register an event listener for the startcallbutton event.

Quick Example

document.addEventListener("startcallbutton", onStartCallKeyDown, false);

function onStartCallKeyDown() {
    // Handle the start call button
}

endcallbutton

This event fires when the user presses the end call button. The event overrides the default end call behavior.

Quick Example

document.addEventListener("endcallbutton", onEndCallKeyDown, false);

function onEndCallKeyDown() {
    // Handle the end call button
}

volumedownbutton

The event fires when the user presses the volume down button. If you need to override the default volume down behavior you can register an event listener for the volumedownbutton event.

Quick Example

document.addEventListener("volumedownbutton", onVolumeDownKeyDown, false);

function onVolumeDownKeyDown() {
    // Handle the volume down button
}

volumeupbutton

The event fires when the user presses the volume up button. If you need to override the default volume up behavior you can register an event listener for the volumeupbutton event.

Quick Example

document.addEventListener("volumeupbutton", onVolumeUpKeyDown, false);

function onVolumeUpKeyDown() {
    // Handle the volume up button
}

activated

The event fires when Windows Runtime activation has occurred. See MSDN docs for further details and activation types.

Quick Example

document.addEventListener("activated", activated, false);

function activated(args) {
    if (args && args.kind === Windows.ApplicationModel.Activation.ActivationKind.file) {
       // Using args.raw to get the native StorageFile object
        Windows.Storage.FileIO.readTextAsync(args.raw.detail[0].files[0]).done(function (text) {
            console.log(text);
        }, function (err) {
            console.error(err);
        });
    }
}

Windows Quirks

  • Original activated event args are available in args.raw.detail[0] property and can be used to get a type information or invoke methods of one of the activation arguments,

  • Original activated event args are also cloned to args.detail[0] and can be used as a fallback in case an inner args property has been lost.
    See https://issues.apache.org/jira/browse/CB-10653 for details.

  • activated event might be fired before deviceready so you should save the activation flag and args to the app context in case you need them - for example in the Share target case. The subscription to the activated event should be done before deviceready handler (in app.bindEvents in terms of the Cordova template).