Sunday, April 11, 2010

Multiline strings and using DroidScript with WebKit

After a walk in the sun, I have uploaded yet a new DroidScript version, have made various enhancements, including multiline strings. JavaScript does not have multiline strings, so I have added that to DroidScript. The syntax is similar to Python, with three quotes to begin and terminate a multiline string.

Below is an example that uses this feature. The example shows how to make a DroidScript app that opens a WebView (a WebKit browser) and displays an HTML document encoded as a multiline string. The example also shows how to use addJavascriptInterface to import Java objects into the WebView, and how to make calls from JavaScript in the HTML document to DroidScript. The JavaScript in the HTML document is executed by the WebKit JavaScript engine, and does not have direct access to the Android class library. The JavaScript code that gets evaluated by DroidScript executes on Rhino, and can therefore use the Android API directly.

The short link to this script is: http://bit.ly/bL1heJ
DROIDSCRIPT_BEGIN
function onCreate(bubble)
{
    var WebView = Packages.android.webkit.WebView;

    var webview = new WebView(Activity);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.addJavascriptInterface(Activity, "activity");
    Activity.setContentView(webview);    
    
    var content =
    """<html>
        <body>
            <script>
            function showToast(message) {
                activity.eval(
                    "var Toast = Packages.android.widget.Toast;" +
                    "Toast.makeText(Activity, '" + message + "', " +
                    "Toast.LENGTH_SHORT).show();"); }
            </script>
            <h1>Take the pill</h1>
            <input 
                type="button" 
                value="Take pill" 
                onclick="showToast('You have taken the red pill!')">
        </body>
    </html>""";
    
    webview.loadData(content, "text/html", "utf-8");
}
DROIDSCRIPT_END

0 comments:

Post a Comment