I'm trying to build an app using cordova but instead of hosting the web app locally, I will host it on a server.
So that part works quite well with the whitelist and allow-navigation.
The issue comes when I try to use the camera. It seems it takes some time before the camera is accessible through the navigator.
So this is my simple web app just to understand how it works.
<!DOCTYPE html>
<head>
<title>test</title>
<script src="scripts/cordova.js"></script>
</head>
<body>
<script>
(function() {
// camera will be undefined
var camera = navigator.camera;
})();
</script>
</body>
</html>
But when I put the whole thing inside setTimeout, it is accessible.
<!DOCTYPE html>
<head>
<title>test</title>
<script src="scripts/cordova.js"></script>
</head>
<body>
<script>
(function() {
setTimeout(function() {
// I can now use it.
var camera = navigator.camera;
}, 10000);
})();
</script>
</body>
</html>
And this is my index.js file, which will redirect to the web app hosted on our server. So it waits for the device ready before redirecting.
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
window.location.replace("http://10.0.0.36:8080/");
},
// Update DOM on a Received Event
receivedEvent: function(id) {
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);
}
};
app.initialize();
I'm trying to understand why?
Thanks,
You need to wait for device ready before you should call any plugins.
document.addEventListener("deviceready", function(){
var camera = navigator.camera;
})