When developing an hybrid application we encounter difficulties when tried to track (debug) code we wrote in Java Script that is executed inside the WebView object. The problem becomes even more complex when using PhoneGap.

The following code sample shows how we can use the android logcat for getting log messages from the code we wrote in Java Script running inside the WebView object.

We first need to define a new class that later we shall bind with the Java Script code running inside the WebView object.

package com.abelski.weblogcat;
import android.util.Log;

public class WebLog 
{
	public int i(String tag, String msg)
	{
		return Log.i(tag,msg);
	}
}

We can now bind an object instantiated from WebLog class with a property dynamically added to the window object (in Java Script). We just need to update the activity we developed with a definition for the onStart call back function.

package org.apache.cordova.example;

import android.app.Activity;
import android.os.Bundle;
import org.apache.cordova.*;

import com.abelski.weblogcat.WebLog;

public class cordovaExample extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.loadUrl("http://www.abelski.com/demo.html");
    }

    @Override
    public void onStart()
    {
    	super.onStart();
    	appView.addJavascriptInterface(new WebLog(),"weblogger");
    }
}

Doing so, the code written in Java Script running inside the WebView object will be able to access a WebLog object when referring window.weblogger. The following is the source code of the demo.html file.

<script type="text/javascript">
var a = 3;
window.weblogger.i("ourtry","a was assigned with 3");
var b = 4;
window.weblogger.i("ourtry","b was assigned with 4");
var sum = a+b;
document.write(sum);
window.weblogger.i("ourtry","sum was assigned with total of a and b");
</script>

The following video clip shows that.

Leave a Reply

Your email address will not be published. Required fields are marked *