Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Calling JavaScript functions in WebView

I am trying to call some javascript functions sitting in an html page running inside an android webview. Pretty simple what the code tries to do below - from the android app, call a javascript function with a test message, which inturn calls a java function back in the android app that displays test message via toast.

The javascript function looks like:

function testEcho(message){      window.JSInterface.doEchoTest(message); } 

From the WebView, I have tried calling the javascript the following ways with no luck:

myWebView.loadUrl("javascript:testEcho(Hello World!)"); mWebView.loadUrl("javascript:(function () { " + "testEcho(Hello World!);" + "})()"); 

I did enable javascript on the WebView

myWebView.getSettings().setJavaScriptEnabled(true); // register class containing methods to be exposed to JavaScript myWebView.addJavascriptInterface(myJSInterface, "JSInterface");  

And heres the Java Class

public class JSInterface{  private WebView mAppView; public JSInterface  (WebView appView) {         this.mAppView = appView;     }      public void doEchoTest(String echo){         Toast toast = Toast.makeText(mAppView.getContext(), echo, Toast.LENGTH_SHORT);         toast.show();     } } 

I've spent a lot of time googling around to see what I may be doing wrong. All examples I have found use this approach. Does anyone see something wrong here?

Edit: There are several other external javascript files being referenced & used in the html, could they be the issue?

like image 424
user163757 Avatar asked Dec 01 '10 14:12

user163757


People also ask

How to use JavaScript in Android WebView?

Enable JavaScript JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView . You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() . WebView myWebView = (WebView) findViewById(R.

Can WebView run JavaScript?

WebView allows you to bind JavaScript code to Android code through an interface. To do this, we must use the addJavaScriptInterface() method, which is passed the class that provides the interface for JS, and the name that will be used to display the instance in JS (for example, “AndroidFunction“).

How to call JavaScript function from Android?

a)Add a Button to Android UI and add onClickListener to it. We will call JavaScript's getValue() method on onClick event of this Button. }); b)Adding Callback function in JavaScriptInterface for MyAndroid.


1 Answers

I figured out what the issue was : missing quotes in the testEcho() parameter. This is how I got the call to work:

myWebView.loadUrl("javascript:testEcho('Hello World!')"); 
like image 93
user163757 Avatar answered Oct 01 '22 06:10

user163757