How to fire deviceready event in Chrome browser (trying to debug phonegap project)

Max picture Max · Jul 14, 2011 · Viewed 35.8k times · Source

I'm developing a PhoneGap application and I'd like to be able to debug it in Chrome rather than on the phone. However, I do the initialization of my code in an onDeviceReady() function that is triggered when PhoneGap fires the "deviceready" event. Since Chrome doesn't fire this event, my code isn't ever initialized.

Here's a stripped down version of my code:

var dashboard = {};

$(document).ready(function() {
    document.addEventListener("deviceready", dashboard.onDeviceReady, false);
}); 

dashboard.onDeviceReady = function() {
    alert("hello!"); //this is never fired in Chrome
};

I've tried using the StopGap code, which basically just does the following:

var e = document.createEvent('Events'); 
e.initEvent("deviceready");
document.dispatchEvent(e);

But when I run that code in the Chrome javascript console, the "hello" alert still doesn't trigger. What am I doing wrong? Or does chrome just not support firing "custom" events like deviceready?

Answer

Chemik picture Chemik · Apr 19, 2012

Add this code to your onLoad handler function:

    if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
        document.addEventListener("deviceready", onDeviceReady, false);
    } else {
        onDeviceReady();
    }

Event "deviceready" is fired in cordova.js so I don't know a way to detect existence of this event in application code.