I am building a PhoneGap App. Unfortunately, when deploying to iOS devices and simulators the deviceready
event never fires. I\'m using Phonegap 2.2.0.
in my html I have a onload that triggers that adding of an event listener to deviceready
function onDeviceReady() {
console.log("we are an app");
MyApp.initialize_phonegap();
}
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
</script>
</head>
<body onload="onBodyLoad()">
It seems to make a difference if you are adding the deviceready listener before or after the cordova.js:
I was not able to find any documentation on this, but cordova.js intercepts calls to addEventListener + removeEventListener and calls only deviceready callbacks which has been added before cordova.js.
Solution in my case was just to rearrange the script order:
<script>
document.addEventListener('deviceready', ...)
</script>
<script src="cordova.js"></script>
I discovered that if you accidentally include the cordova.js script twice, then the deviceready event does not fire.
I was having the same issue. I got it to work by adding the device plugin.
$ cordova plugin add org.apache.cordova.device
To verify:
$ cordova plugin ls
To add to olore's answer I ended up using the approach that the code in the default project (that gets built from the ./create
script) uses (which is different to the code in the Event docs).
The major differences are (I do not really know which one of these actually are to be taken into account):
cordova-2.2.0.js
is located in the root folder<script>
s are included right before the closing </body>
-tag and not in the document's head
deviceready
-handling works like:
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
myApp.start(); //this is where I put the call to my App's functionality relying on device APIs
},
// Update DOM on a Received Event
receivedEvent: function(id) { // I didn't really use this, yet I left it in here as it's in the demo
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
The last <script>
tag just calls app.initialize()
This seems to work quite fine on iOS and Android and is a little more understandable to me than the double handler nesting from the docs.