Custom JavaScript alerts in iOS using PhoneGap HTML

14,318

Solution 1

Like Simon said check out the notifications it's part of the phonegap API.

You call it like this -

Notification with options:

navigator.notification.confirm(
   "This is my Alert text!",
    callBackFunction, // Specify a function to be called 
    'Alert Title',
    ["Ok", "Awesome"]
);

function callBackFunction(b){
  if(b == 1){
    console.log("user said ok");
  }
  else {
    console.log("user said Awesome");
  }
}

A simple notification -

navigator.notification.alert(
    "This is my Alert text!",
    callBackFunctionB, // Specify a function to be called 
    'Alert Title',
    "OK"
);
function callBackFunctionB(){
    console.log('ok');
}

Hope that helps!

Solution 2

To be able to test on both a desktop browser and PhoneGap application, I suggest to use a dynamic approach as such:

function showMessage(message, callback, title, buttonName) {

    title = title || "default title";
    buttonName = buttonName || 'OK';

    if(navigator.notification && navigator.notification.alert) {

        navigator.notification.alert(
            message,    // message
            callback,   // callback
            title,      // title
            buttonName  // buttonName
        );

    } else {

        alert(message);
        callback();
    }

}

Solution 3

Use navigator.notfication.alert as you can provide your own title.

Share:
14,318
Blynn
Author by

Blynn

App and Web Developer.

Updated on June 05, 2022

Comments

  • Blynn
    Blynn about 2 years

    My app has a couple of JS alerts and it seems to always display the page name like.

    index.html

    Is there a way to change the index.html to my App's name or custom text.

    Example:

    My App // Which replaces .index.html
    alert("I am an alert box!");
    
  • JOM
    JOM over 11 years
    This is the best answer, supports BOTH desktop and PhoneGap!
  • Zorayr
    Zorayr about 11 years
    Glad you found it useful @JOM!
  • igo
    igo about 11 years
    Actually instead of invoke(callback) should be callback(). Otherwise you get error invoke is not defined
  • Zorayr
    Zorayr about 11 years
    That's correct @igo, invoke is actually a reusable method that I wrote somewhere else that only invokes callback if it's defined.
  • mavericks
    mavericks over 8 years
    It's not showing anything, I tried by installing cordova-plugin-vibration and cordova-plugin-dialogs plugins for ios Application, any idea..?!
  • Ashwin G
    Ashwin G almost 8 years
    My cordova app uses location services, so iOS throws a default alert for user persmission which has app directory..index.html. How to fix this?