Thursday, October 20, 2011

Call JavaScript inside WebView from Android activity, with parameter passed.

The last exercise "Run Android Java code from Webpage" show how to call from WebView JavaScript to Android activity. Here will show how to call in reverse direction: Call JavaScript inside WebView from Android activity, with parameter passed.

Call JavaScript inside WebView from Android activity, with parameter passed.

/assets/mypage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>
<p id="mytext">Hello!</p>
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<input type="button" value="Open Dialog" onClick="openAndroidDialog()" />
<script language="javascript">
   function showAndroidToast(toast) {
       AndroidFunction.showToast(toast);
   }

   function openAndroidDialog() {
       AndroidFunction.openAndroidDialog();
   }
  
   function callFromActivity(msg){
 document.getElementById("mytext").innerHTML = msg;
   }
</script>

</body>
</html>


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<EditText
   android:id="@+id/msg"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content" />
<Button
 android:id="@+id/sendmsg"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Msg to JavaScript"
   />
<WebView
   android:id="@+id/mybrowser"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
  />
</LinearLayout>


main code:
package com.exercise.AndroidHTML;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AndroidHTMLActivity extends Activity {
 
 WebView myBrowser;
 EditText Msg;
 Button btnSendMsg;
 
 /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       myBrowser = (WebView)findViewById(R.id.mybrowser);
      
       final MyJavaScriptInterface myJavaScriptInterface
        = new MyJavaScriptInterface(this);
       myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
      
       myBrowser.getSettings().setJavaScriptEnabled(true); 
       myBrowser.loadUrl("file:///android_asset/mypage.html");
      
       Msg = (EditText)findViewById(R.id.msg);
    btnSendMsg = (Button)findViewById(R.id.sendmsg);
    btnSendMsg.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    String msgToSend = Msg.getText().toString();
    myBrowser.loadUrl("javascript:callFromActivity(\""+msgToSend+"\")");
    
   }});

   }
  
 public class MyJavaScriptInterface {
  Context mContext;

     MyJavaScriptInterface(Context c) {
         mContext = c;
     }
    
     public void showToast(String toast){
         Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
     }
    
     public void openAndroidDialog(){
      AlertDialog.Builder myDialog
      = new AlertDialog.Builder(AndroidHTMLActivity.this);
      myDialog.setTitle("DANGER!");
      myDialog.setMessage("You can do what you want!");
      myDialog.setPositiveButton("ON", null);
      myDialog.show();
     }

 }
}


Download the files.

Updated: Read the updated example with @JavascriptInterface.


20 comments:

  1. if URL like this
    file:///android_asset/mypage.html?para=1

    that time it is not working .
    How to solve this problem help me

    ReplyDelete
  2. why do we need to surround the variable msgToSend within quotes??

    ReplyDelete
  3. After to remove java's ", the parameter passed to myBrowser.loadUrl() become javascript:callFromActivity("msgToSend").

    So "msgToSend" is passed to javascript:callFromActivity() as a String.

    ReplyDelete
  4. Good tutorial... Will try to do something crazy with this. i really appreciate you..!!

    Regards,
    Amith Nagraj

    ReplyDelete
  5. Very nice demo. FYI, as of API 17, be sure to mark your JS interface's methods with @JavascriptInterface so they are visible.

    ReplyDelete
  6. great explanation great help this will be in my project. thnx man.

    ReplyDelete
  7. thanks for your valuable information

    ReplyDelete
  8. Hey hi ,
    This program is really nice but i tried many times but sorry not working dont no wht is a problem.
    I an trying to create html file and js file plz help me

    ReplyDelete
  9. hello Anuprita Kasbekar,

    Are u cannot run Java code from Javascript? Have to add @JavascriptInterface in your Java methods?

    Please read updated post: Calling between Android Java methods and WebView JavaScript, with @JavascriptInterface.

    ReplyDelete
  10. Hello Eric,
    it was something i was searching for
    ...nice post .i want something exactly opposite to this..i want to get some result thro php..i want to pass this result(simply can be id or name through query) as jscript variable and then want to show this result on android screen using android Dialog...i tried but unsuccessful...Please help me..

    ReplyDelete
  11. Very easy to follow example, and to the point. Thank you!

    Could you please improve it by giving us an example of how to return error code from JavaScript to Java/Android?

    ReplyDelete
  12. U helped me a lot its working for me.... :) thnq :)

    ReplyDelete
  13. what is use for AndroidFunction.openAndroidDialog(); in java script. when i was written another function in java script it is not showing with out i am placed AndroidFunction.openAndroidDialog();. how can i resolve

    ReplyDelete
  14. in all these cases you have control ver the webview or the webpage. but i dont own the webpage. so what should i do then. is this code will work in that case.

    ReplyDelete
  15. hello, i want to host my javascript of quiz on android apk.
    can u please guide me how to call the javascript from the webview from the apk. my app path is. App-name\app\src\main\assets\bootstrap\js\quiz.js. when i load my website from the apk then the javascript should work. how to do this??

    ReplyDelete
  16. Thank you. This was really usefull

    ReplyDelete
  17. hey Guys!
    Does anybody know how to make this work on a fragment?
    Instead of calling everything from the main activity.
    Thanks!!

    ReplyDelete
  18. Need Help!!! callFromActivity not working for me

    ReplyDelete