Reputation: 103
I would like to listen on events such as Application closing and Device shut down to run some code (such as logout feature) before the Application closes or the Device shut down / sleep events.
Is this possible with Cordova/Phonegap? I looked for plugins and I found plugins about PowerManagement related events but nothing about these events.
thanks
Upvotes: 2
Views: 3324
Reputation: 3803
You're not able to listen on events like onAppClose
nor onDeviceShutdown
or onExit
- these events don't exist.
There are events which can be triggered by adding an eventListener
to your code.
DeviceReady Eventlistener
document.addEventListener("deviceready", yourCallbackFunction, false);
The yourCallbackFunction
will fire when your device has entered the deviceready
state.
A Documentation about the eventListeners given you from Cordova/Phonegap can be found here: Cordova - Eventlistener Documentation
As BipBip said in his answer, that there could be a possibilty to trigger such events with the onunload
attribute inside the body
tag, i just tested that inside a clean cordova application.
<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">-->
<!-- <meta name="format-detection" content="telephone=no">-->
<!-- <meta name="msapplication-tap-highlight" content="no">-->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body onload="alert('onload fired');" onunload="alert('onunload fired');">
<script type="text/javascript" src="cordova.js"></script>
</body>
</html>
So onunload
never fired (nor if you replace the alert
with a console.log()
) because cordova apps that get totaly closed will never fire such events.
An alternative to all of this behaviours could be the onPause
eventListener. This one fires instantly after the user switches the application or taps the home button to get to the homescreen. That one gets implemented by:
document.addEventListener("pause", onPauseFired, false);
Upvotes: 2
Reputation: 2673
I think this links provide what you want about a Cordova life Cycle :
http://simonmacdonald.blogspot.fr/2011/04/phonegap-lifecycle-events.html
When you application exits the unload event is called. This is a useful event if your application needs to save some state data. You would register your unload listener the same as you would for the load event by adding it to the body tag.
<body onload="onLoad()" onunload="onUnLoaded()">
Upvotes: 1