How to use the native Alert dialog in PhoneGap
An important part to any application is issuing a simple alert to your user. Whether it’s to tell them about an error that just occurred, or if you need to ask them a simple question, giving a message to your user is about the most basic part of any app.
Sadly, when you try to rely on the ever faithful “alert()” function in JavaScript inside a PhoneGap application, you’ll notice the alert box it shows is titled with a very unprofessional “index.html” across the top. Not only does it make it obvious that the app they’re interacting with is actually HTML-based, but you can’t convey the importance of one message or another with a title. Most people only ever read the title anyway, so in order to provide this capability to your application, PhoneGap has an answer for this problem.
Inside PhoneGap there’s a class called “Notification” which is used for, well, sending notifications to your user. And, by calling:
navigator.notification.alert(
message,
title,
buttons...,
options);
Everything, except for the message, is optional. The more arguments you provide, the more you can customize the alert box. For instance, if you don’t supply a button label, one single “OK” button will be created. Want to ask a Yes/No question? Simply pass two labels for their respective button names.
Like other functions in PhoneGap, the alert notification can be passed an “options” object that allows you to give it more information, such as an onClick callback.
That example shows how to ask your user what to do in the event of an Internet connection problem. You’ll notice that I’ve decided to pass two button labels. In the onClick callback function I supplied in my options argument, I’m checking the “buttonIndex” variable it passes. This tells your function which button was pressed. If you want more than 2 buttons, just list multiple labels and it will show as many as can fit on the screen.
A very simple function, but invaluable as a developer resource. And, more importantly, a very easy and professional way to get feedback from your user.