4

I have created an application in which i am using webview and loading a simple static html page. I am calling a java script function from activity but i am unable to call a function from java script. I have tried few of the link , but it didn't work .
Javascript Callback function pass to Android
I cannot call an android function from javascript
Here is my code. Thank you in advance.


acitivity_main.xml

<Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call JavaScript Function"
        android:onClick="callJavaScript" />

<WebView
    android:id="@+id/myWebView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

index.html

<html>
<head>
<script type="text/javascript">
        function displayMessage(){
            document.getElementById('test1').innerHTML = 'This is from java script.';
            Android.returnResult();
        }
    </script>
</head>
<body>
    <h1 id="test1">Hello World</h1>
</body>
</html>

Main activity has following two functions .

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView) this.findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.addJavascriptInterface(new JavaScriptHandler(this), "Android");
        myWebView.loadUrl("file:///android_asset/index.html");
    }

    public void callJavaScript(View view) {
        Log.v(null, "Calling java Script");
        myWebView.loadUrl("javascript:displayMessage()");
    }

This is the JavaScriptHandler class

public class JavaScriptHandler {
    Context mContext;

    public JavaScriptHandler(Context context) {
        mContext = context;
    }

    public void returnResult() {
        Log.v(null, "result received");
    }
}
2
  • Kindly add alert statements in your javascript method to see if you javascript method is getting called properly. Otherwise I dont see any problem in your implementation. Commented Nov 27, 2013 at 13:54
  • Thank you for replying , i have added a line to change the html text when java script is getting called and it was working anyway i got the answer looks like i had to use the annotation. Commented Nov 28, 2013 at 4:51

1 Answer 1

5

Make it

@JavascriptInterface
public void returnResult() {
    Log.v(null, "result received");
}

This annotation allows exposing methods to JavaScript.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.