HTML5 Web Apps on Mobile Devices

Get out your Buzzword Bingo cards, we’re talking HTML5. And Canvas2D. And WebGL. See? Check them off and then continue reading. So, while writing “native” apps using JavaScript is definitely possible and works great with QML, some games are just simple enough (or want to have a broad enough audience) to warrant writing everything in HTML5.

This might also be a good time to check off XmlHttpRequest on your BB card, even if none of the following games use it – you might want to use it in your applications or game for things such as server-side stored high scores.

As far as Maemo and MeeGo is concerned, you might want to try out some of these games (especially the WebGL variant of One Whale Trip) in Fennec (aka Mobile Firefox – get it for: N900, N950/N9, Nemo Mobile).

Color Lines: This one simply uses Canvas2D, and works nicely on all mobile browsers that I tested – Maemo, MeeGo, Android, WP7.5, BB Playbook, iOS. Comes in at about 650 lines of rather well-documented JavaScript, and could easily be ported to use QML as a renderer if need be (it would be good to have a QML Plug-In that provides a JavaScript context + (a subset of) the Canvas2D API – without using WebKit (cross that off, too), that is). Also, the N900′s stock browser has performance problems rendering this, while on the same device in Fennec it’s quite playable.

Circle1D: This is a straight Python-to-JavaScript port of a lame 2D “Physics” Engine. It’s kept very (read: very, very) simple, and collision detection could be done in a nicer way, but the inefficiency of it provides a nice benchmark for comparing JavaScript engine performance (I’m sure you can find “engine performance” on your bingo card as well) on mobile devices. The N900′s default browser can’t handle it at all, but Fennec can at least render/simulate it, albeit slowly.

One Whale Trip: This game actually started out as a Python game for PyWeek last September, which was also ported to the N950/N9, but as a test for trying out WebGL, I decided to port it from Python/PyGame to JavaScript/Canvas2D and then to WebGL (the Python version also contains two renderers – a “blitting” one using PyGame surfaces, and an OpenGL one using OpenGL [ES 2 on mobile]). The Canvas2D version works again in all modern mobile browsers (same as above), the WebGL only works on browsers supporting WebGL, for example Fennec/Firefox on both the N900 (even though very slowly) and not in any of the stock browsers (even not the one on the N9). As WebGL is “roughly” the same as OpenGL ES 2.x, one could imagine sharing at least shader programs for a possible C++-or-JavaScript cross-platform application.

So yeah, for smaller applications and/or games, HTML5 is definitely an option. In Firefox OS, your HTML5 web app will – also with WebGL – work and integrate nicely as “native” app. If you also want to create “native” applications (maybe after finishing the HTML5 version), consider encapsulating your JavaScript code so that you can re-use it in QML code, or (in case of WebGL apps), at least design the rendering part of your application in such a way that the code/architecture and shader programs can be shared with a C++ port of your existing HTML5 app.

Another option that’s worth considering: Writing a compatiblity application layer that can load (specially-crafted) WebGL subset applications and display them on a fullscreen SDL-(or Qt)-provided window. Applications written in this WebGL subset could then be deployed on the web as HTML5 application or “natively” running on top of a JavaScript engine only. I’d call that “webglenv“, and no, I haven’t written it yet.

How to debug Windows Phone HTML5 Apps

  Debugging HTML applications is never an easy task and until today I did not know how to approach this for Windows Phone HTML5. The technique I will describe in this post can be applied also for Windows Phone 7.1 applications using Phonegap or Android/iOS applications.
   The “secret” tool for debugging the html content inside our applications is called WEINRE which comes from WEb INspector REmote. Weinre is a debugger for web pages, like FireBug (for FireFox) and Web Inspector (for WebKit-based browsers), except it’s designed to work remotely, and in particular, to allow you debug web pages on a mobile device such as a phone. 
    In order to install Winre you will need to download and install NodeJS

    Once you have installed NodeJS restart your machine this way you will be able to run the NodeJS commands from the command prompt. After restart open a command prompt window and run this command:
 npm install weinre -g  
This will install the Weinre package globally. This is what you should see in the Command Prompt window:

    When the installer has finished its work you are ready to run the Weinre server on your PC. Execute this command from the Command Prompt:
 weinre --boundHost -all- --debug -true  
    With these parameters Weinre should also open the firewall port. For more parameters have a look at this page. You can verify if the server started by opening a browser page and loading 127.0.01:8080 (8080 is the default port for Weinre). If you are seeing this page then the server is running:
   Now click on the Debug Client User Interface link where you will be able to see if any client is connected and debug the connected clients.
    Let’s create the Windows Phone HTML5 application. Use the SDK template to create a new project, open the page index.html inside the folder Html and add this line to the head section:
 <script src="http://[the server ip]:8080/target/target-script-min.js#anonymous"></script>  
replace [the server ip] with the IP of the PC running the Winre server and run the application. If everything went as we expected in the Debug Client user Interface on the Server we should see one Target connected:

    Once the target Windows Phone page is connected you can inspect and change the DOM in real-time, execute javascripts:

 

 
    In this particular case I’ve only changed the background of the page but you can do whatever you want. Here you can find further details on how to use the Server User Interface.
    Using the Console panel you can execute arbitrary JavaScript expressions/statements. It also shows the output from various console methods, like console.log().

 

    This is pretty much everything. Simple and veryyyyyy useful if you need to debug your HTML5 windows phone applications.
    As usual don’t hesitate to contact me if you have further questions.

NAMASTE

El modelo de plantilla de proyecto HTML5 en Windows Phone 8 y II

Esto mas que una entrada como dios manda, es simplemente una advertencia en toda regla, sobre un gravísimo error en esta plantilla.

Si alguno de vosotros a intentado usarla, podrá ver que tanto el método InvokeScript como el evento ScriptNotify no funcionan. Es mas si en el código HTML que cargamos en nuestro WebBrowser tenemos cualquier tipo de código de script, este tampoco funcionará.

En mi anterior post os había comentado que nuestro WebBrowser tenia por defecto deshabilitada la opción de cargar y ejecutar cualquier tipo de script, pero que simplemente indicando a true la propiedad IsScriptEnabled de dicho control, todo funcionaria.

Bueno, pues como todos habréis visto en la plantilla que Visual Studio nos crea, una de las primeras líneas de código, concretamente en el evento Loaded del WebBrowser, viene pre escrito concretamente esto

private void Browser_Loaded(object sender, RoutedEventArgs e)
{
    // Add your URL here
    Browser.Navigate(new Uri(MainUri, UriKind.Relative));
    Browser.IsScriptEnabled = true;
}

Con lo que ya nos podemos imaginar que la comentada propiedad IsScriptEnabled, esta perfectamente indicada.

Pues bien, este código no funciona ya que dicha propiedad debemos de indicarla o cambiar su valor antes de realizar la navegación para que surta efecto. Para solventar este problema simplemente deberemos de establecer la propiedad a true directamente en las propiedades del control dentro del código XAML.

<phone:WebBrowser x:Name="Browser"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"
            Loaded="Browser_Loaded"
            IsScriptEnabled="True"
            NavigationFailed="Browser_NavigationFailed" />

Es una opción, existen otras, pero quizás sea la mas sencilla.

Comencé diciendo que era un error gravísimo y así me lo parece, ya que cualquier neófito puede pasarse mucho tiempo hasta que descubra que todo su código no funciona simplemente por un error de bulto de quien a diseñado esta plantilla.

Bueno esperemos que dentro de no mucho la corrijan. Pero de momento basta con saberlo y poder solucionar el problema..

Bueno seguiré hablando en sucesivas entradas de la programación HTML dentro de Windows Phone, aunque pueda perder amigos por el camino…… ;-( 

El modelo de plantilla de proyecto HTML5 en Windows Phone 8

Una de las nuevas características que incorpora Windows Phone 8, es el flamante nuevo navegador Internet Explorer 10 en su versión móvil. Según nos cuenta el equipo de producto, este es una versión no muy alejada, (otros dicen que es exactamente la misma), que su hermano mayor la versión de escritorio incorporada en Windows 8. Aquí tenéis un pequeño repaso de dicho navegador desde wpcentral.com

Bueno la cuestión es, que el nuevo SDK de Windows Phone 8, incorpora una nueva plantilla de proyecto la cual se denomina “Windows Phone HTML5 App”.

Sin título-1

Esta plantilla no es mas que una pagina de Windows Phone, con un componente WebBrowser incorporado, una serie de eventos de la misma ya creados y una carpeta denominada HTML en donde nos encontramos con una estructura de web básica.

Sin título-2

Disponemos de la posibilidad de interactuar desde la web que se visualiza en el WebBrowser, con nuestro sistema a través del evento ScriptNotify, y desde nuestra aplicación con la pagina web usando el método InvokeScript.

Vamos a poner un ejemplo muy sencillo. Realizaremos algunos cambios en el código creado por la plantilla para mostrar el control WebBrowser, un textbox y un simple boton. La idea es mostrar en la web incrustada en el WebBrowser lo que le indiquemos en el textbox y mostrar un MessageBox de Windows Phone cuando interactuemos con la web.

Sin título-4

 

Y nuestro código HTML que mostraremos en el WebBrowser tendrá una pinta como esta:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="/html/css/phone.css" />
        <title>Windows Phone</title>

      <script type="text/javascript">
        function IncorporarTexto(data) {
          container.innerText = data;
        }
      </script>
    </head>
    <body>
      <div id="container">
        El texto Aquí.
      </div>
    </body>
</html>

Ahora simplemente deberemos de llamar al método InvokeScript desde el evento Click de nuestro botón, pasando como parámetro al script de la pagina web el texto contenido en el TextBox, de la siguiente forma.

private void Boton1_Click(object sender, System.Windows.RoutedEventArgs e)
{
    if (loadCompleted == true)
    {
        Browser.InvokeScript("IncorporarTexto",TextBox1.Text);
    }
}

Vemos en el anterior trozo de código que disponemos de una variable para controlar si la pagina esta totalmente cargada o no, ya que el método InvokeScript solo funcionará de forma correcta cuando el HTML a cargar en el WebBrowser haya terminado totalmente de cargarse. Para ello podremos controlar esto subscribiéndonos al evento LoadCompleted de nuestro WebBrowser.

private void Browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    loadCompleted = true;
}

Ok, perfecto ya sabemos como podemos interactuar desde nuestra aplicación y desde nuestro código C# en los scripts de nuestra pagina web que acabamos de cargar.

Solamente una cosa mas, nuestro componente WebBrowser por defecto tiene deshabilitada la capacidad de ejecutar scripts en el código HTML que se carga. Para poder habilitar dicha capacidad debemos de indicar a true la propiedad IsScriptEnabled de dicho componente WebBrowser.

Sin título-7

La siguiente opción que hemos comentado es la capacidad del código HTML cargado por el componente WebBrowser para interactuar con nuestro sistema, mediante el control del evento ScriptNotify del propio WebBrowser.

Vamos a modificar nuestro código HTML, para crear una nueva función en JavaScript e incorporar un botón que dispare dicha función.

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link rel="stylesheet" type="text/css" href="/html/css/phone.css" />
        <title>Windows Phone</title>

      <script type="text/javascript">
        function IncorporarTexto(data) {
          container.innerText = data;
        }
        
        function SaludarAlTelefono() {
          var texto = "Hola WP8 desde JS";
          window.external.notify(texto);
        }
        
      </script>
    </head>
    <body>
      <div id="container">
        El texto Aquí.
      </div>
      <hr/>
      <button onClick="SaludarAlTelefono()">Saludar</button>
    </body>
</html>

Como podemos ver para realizar esta acción usamos el objeto de JavaScript, window.external, concretamente el método notify, el cual es el encargado de disparar el evento ScriptNotify del WebBrowser.

private void Browser_ScriptNotify(object sender, 
                   Microsoft.Phone.Controls.NotifyEventArgs e)
{
    MessageBox.Show(e.Value);
}

Dentro de los argumentos que nos entrega el evento, disponemos de la propiedad Value, que nos trae el valor del parámetro que hayamos indicado en la instrucción de JavaScript.

Sin título-8

Los ejemplos que he puesto son muy simples, pero las posibilidades son enormes. Ahora viene lo bueno. Todo el mundo debería de saber que esto ya lo podíamos hacer con Windows Phone 7.5, hasta aquí no existe absolutamente nada nuevo que incorpore Windows Phone 8. Si es verdad que quizás esta característica del control WebBrowser no era muy conocida, pero como os comento no hay nada nuevo.

¿Cual es entonces la función real de esta plantilla? Pues sinceramente lo desconozco. Tal vez el equipo de producto quiso hacer creer que igual que en Windows 8 disponemos de un tipo de programación en JavaScript, en Windows Phone 8, también lo tendríamos. Pero no, nada de WinJS a la vista.

Bueno realmente tengo que decir que lo novedoso de todo esto es la incorporación de IE10 al sistema. Es de suponer que con esta versión del navegador vamos a poder explotar en un grado muy alto todas las capacidades que HTML5 incorpora. Podéis desde el propio emulador acceder a http://ie.microsoft.com/testdrive y ver todos los test que IE10 en su versión móvil pasa con muy buena nota.

Sin título-3

Así mismo en la documentación del SDK de Windows Phone 8, en la sección en la que se habla de este tipo de plantilla, se nos indica que consultemos la guía para desarrolladores de Internet Explorer 10, para poder sacar todo el potencial que los desarrolladores HTML disponen en Windows Phone 8.

Protractor (Featured Project)

Protractor  is a HTML5 application for Windows Phone. As the name suggest this application allows the device screen to be used as a protractor to measure length and angles of a geometric object. It also has the option to change the measuring units to Inch and mm.

HTML5 Canvas is used to perform all the drawing in the application which runs on Silverlight WebBrowser element.  This project could be a nice example for newbie to have a hands on experience on HTML5.

– Somnath Banik (on behalf of the Projects Moderation team)