Skip to content

Instantly share code, notes, and snippets.

@soemarko
Created November 27, 2011 06:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soemarko/1397078 to your computer and use it in GitHub Desktop.
Save soemarko/1397078 to your computer and use it in GitHub Desktop.
Using webview to use prompt window with Titanium
var btn = Ti.UI.createButton({
title: 'Prompt!',
height: 40,
width: 100,
top: 20
});
var lbl = Ti.UI.createLabel({
text: 'Label',
textAlign: 'center'
});
var wv = Ti.UI.createWebView({
url: 'prompt.html',
visible: false
});
var win = Ti.UI.createWindow({
backgroundColor: '#cecece',
title: 'Window'
});
win.add(btn);
win.add(lbl);
win.add(wv);
btn.addEventListener('click', function(e) {
wv.evalJS('doPrompt()');
});
Ti.App.addEventListener('app:prompt', function(e) {
lbl.text = 'prompt> ' + e.data;
});
win.open();
<html>
<head>
<title>Prompt!</title>
<script>
function doPrompt() {
var x = prompt('Question for prompt:');
if(x && x != '') { /* ignoring 'Cancel' or empty string */
Ti.App.fireEvent('app:prompt', {data: x});
}
}
</script>
</head>
<body></body>
</html>
@benoitzohar
Copy link

Thanks a lot for this !

i made a function out of it (which is independant and doesn't have the "prompt.html" title on the dialog) :

     /*
 * tprompt() : prompt the user for a string input (using a fake webview to simulate a standard javascript prompt)
 * param:   handler     Ti's View/Window : view handling the fake webview
 * param:   question    String      question to ask to user
 * param:   valid_cb    Function    Callback function : called when the user entered something and hits OK
 * param:   cancel_cb   Function    Callback function : called when string is empty of user clicked cancel
 */
tprompt = function(handler,question,valid_cb,cancel_cb) {
    if (!handler || !valid_cb) return false;

    if (!question) question = '';

    var wv = Ti.UI.createWebView({
        html : '<html><head></head><body><script>Ti.App.fireEvent("app:prompt",{data:x});</script></body></html>',
        visible: false
    });

    var callback_fn = function(e) {
        if (e.data && e.data !='' && valid_cb) {
            valid_cb(e.data);
        }
        else if (cancel_cb){
            cancel_cb();
        }

        handler.remove(wv);

        // remove event listener
        Ti.App.removeEventListener('app:prompt',callback_fn);
    };

    Ti.App.addEventListener('app:prompt', callback_fn);

    wv.evalJS("x=prompt('"+question+"');");
    handler.add(wv);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment