Adil Waqar Adil Waqar - 26 days ago 8
Javascript Question

Android Web Console Uncaught ReferenceError

I am calling a native android function via java script loaded in a webview but is not working
Here is what i have done with WebView

paintView = (WebView) findViewById(R.id.webView1);
WebSettings Websettings = paintView.getSettings();
Websettings.setBuiltInZoomControls(true);
Websettings.setSupportZoom(true);
Websettings.setJavaScriptEnabled(true);
Websettings.setBuiltInZoomControls(true);
Websettings.setRenderPriority(RenderPriority.HIGH);
paintView.getSettings().setPluginState(PluginState.ON);
paintView.setWebChromeClient(new WebChromeClient());
final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this);
paintView.loadUrl("file:///android_asset/index_jQueryMobile.html");


and here is the android method

@JavascriptInterface
public void byteToImage(String base64img, String ImageName) throws IOException
{
byte[] pdfAsBytes = Base64.decode(base64img.toString(), 0);
File file = new File(Environment.getExternalStorageDirectory()+"/AndroPaint");
if(!file.exists()) {
file.mkdirs();
}
File filePath = new File(Environment.getExternalStorageDirectory()+"/AndroPaint/"+ImageName+".png");
FileOutputStream os = new FileOutputStream(filePath, true);
os.write(pdfAsBytes);
os.flush();
os.close();
}


and here is the JS function

function getImageBytes()
{
var canvas = document.getElementById('canvas');
var imageName = document.getElementById('imgName');
var imgData= canvas.toDataURL();
activity.byteToImage(imgData,imageName);
}


here is the exception

01-04 10:48:50.409: E/Web Console(15681): Uncaught ReferenceError: activity is not defined:72

Answer

You made a connection interface MyJavaScriptInterface, but you forgot to attach it to the WebView:

paintView.addJavascriptInterface(new MyJavaScriptInterface(this), "activity");

That is why you are getting activity is not defined error. activity object cannot be found by JS engine.

Here is a small tutorial on that