Reputation: 42757
Like others, I'm trying to tell the difference between javascript code running in a mobile browser and in a phonegap webuiview. The standard solution is to wait for the deviceready
event to fire, because after it fires, you know you're in phonegap. But how long do you wait?
I have code I want to run as early as possible because I don't want my users to sit around waiting. But I don't want to run it before phonegap is initialized, if it's going to initialize. What I'm looking for is something like a devicenotready
event which fires when the after cordova.js
code has run and determined there's nothing for it to attach to. Or some variable I can poll to tell the difference between cordova still loading and cordova having given up trying to load. Is there a difference?
I hate this solution, but it's the best I've come up with. Please tell me there's something better than this:
function whenLoaded(callback,timeout) {
var when_loaded_needs_running = true;
document.addEventListener('deviceready', function() {
if( when_loaded_needs_running ) {
when_loaded_needs_running = false;
callback();
} else {
console.log("deviceready fired too late. whenLoaded already ran.");
}
});
window.setTimeout(function() {
if( when_loaded_needs_running ) {
when_loaded_needs_running = false;
console.log("deviceready didn't fire after "+timeout+"ms. running whenLoaded anyway.");
callback();
}
}, timeout);
}
Upvotes: 1
Views: 556
Reputation: 2312
A simpler test would be to see if the cordova
JavaScript global is available - no waiting on an event, you can execute immediately (as long as it executes after the theoretical <script>
include of cordova.js). Depending on which version of PhoneGap you are running, you may need to test one of several global variables.
Should be as simple as:
if(cordova || Cordova || PhoneGap) {
alert('hey im in a phonegap webview!');
} else {
alert('regular old browser, aw shucks');
}
Upvotes: 2