31

I'm loading below html in my webView

https://mail-attachment.googleusercontent.com/attachment/?ui=2&ik=25c0c425c6&view=att&th=138db54ff27ad34b&attid=0.1&disp=inline&realattid=f_h5ahtmbe0&safe=1&zw&saduie=AG9B_P9YNooGjsk_jLefLptQ9q15&sadet=1343790299575&sads=-yBVsLKP_2mh7zMfYLCF7sL1u-w

Now what I want to do is to fill the textbox in the html that came from my java class variable and then automatically hit submit.

But I don't have any idea how to do this.

Any thougths will be appreciated.

Levon Petrosyan
  • 8,815
  • 8
  • 54
  • 65
User
  • 453
  • 1
  • 8
  • 15
  • WARNING: To those thinking `loadUrl` is the way to go, check out the answer with `evaluateJavascript` in it. It's easy to overlook. – Daniel F Dec 03 '19 at 09:00

6 Answers6

58

First, your URL seems not available.

If you want to do data exchange between android app and your web app/web page you can achieve this via javascript.

Here is an example from Android official site:

Create a class like this:

public class JavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

In your WebView:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

In your web page:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
    function showAndroidToast(toast) {
        Android.showToast(toast);
    }
</script>

If you wanna pass something to your webpage, just calling corresponding javascript function:

String str = "xxx";
myWebView.loadUrl("javascript:xxx('"+str+"')");

Here is the Reference: http://developer.android.com/guide/webapps/webview.html

hungr
  • 2,086
  • 1
  • 20
  • 33
  • 4
    what do you mean by this myWebView.loadUrl("javascript:xxx('xxx')"); I'm also using load url to load my html so it is ok to use load url for a multiple times? – User Aug 01 '12 at 04:52
  • 2
    yes as long as the javascript function exists in your web page – hungr Aug 01 '12 at 05:12
  • 1
    I see that's why I will load the javascript because it has the code to pass some data. – User Aug 01 '12 at 05:20
  • 1
    please try and see if there is any problem;) – hungr Aug 01 '12 at 08:13
  • 1
    I' using this like what you said web.loadUrl("javascript:holder(Test!)"); But I don't know how to get the value and assign it in html textbox – User Aug 01 '12 at 08:21
  • 1
    just write the javascript function to set the value you passed to html – hungr Aug 02 '12 at 02:00
  • 1
    just like this codes? document.getElementById("d").innerHTML="String" – User Aug 02 '12 at 02:09
  • 8
    Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher. – Happy Dev Jul 09 '14 at 02:43
  • 1
    @Happydev Thanks I'll update the answer accordingly ;) – hungr Jul 09 '14 at 03:50
  • Can the Java method I call from the JavaScript return a value, and can I use that value in the JavaScript? – Bowi Apr 10 '17 at 13:14
  • How to listen **xxx** function in `component` instead `index.html` – Iman Marashi Jul 15 '21 at 10:59
30

I would add that the load of the javascript function should be done when the html is loaded. To control that, you can use the following:

webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/test.html");
webview.setWebViewClient(new WebViewClient(){
    public void onPageFinished(WebView view, String url){   
        webview.loadUrl("javascript:init('" + theArgumentYouWantToPass + "')");
    }           
});

test.html

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
</head>

<body>
hola
adios
</body>

<script type="text/javascript">

    function init(val){
// Do whatever you want with your parameter val
    }
</script>
</html>

Taken from Uncaught ReferenceError: myFunction is not defined at null:1 Android exception in webview

Community
  • 1
  • 1
AlvaroSantisteban
  • 5,256
  • 4
  • 41
  • 62
6

Just enable DOM Storage and write var x= to string:

webview.getSettings().setJavaScriptEnabled(true);
web.getSettings().setDomStorageEnabled(true);

webview.loadUrl(urlString);
webview.setWebViewClient(new WebViewClient(){

public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);

    String js = "javascript:var x =document.getElementById('username').value = '"+user+"';var y=document.getElementById('password').value='"+pass+"';";

    if (Build.VERSION.SDK_INT >= 19) {
        view.evaluateJavascript(js, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
            }
        });
    }
    else {
        view.loadUrl(js);
    }
}
Daniel F
  • 13,684
  • 11
  • 87
  • 116
Denish Rana
  • 101
  • 2
  • 11
  • This is the best answer. I was trying to pass a 5MB JSON string to the WebView, and `loadUrl` wasn't capable of doing so. `evaluateJavascript`, on the other hand, had no issues with this. – Daniel F Dec 03 '19 at 08:55
4

Be careful to call javascript function like this, the str may include single quote or other special characters.

String str = "xxx";
myWebView.loadUrl("javascript:xxx('"+str+"')");

I suggest to encode the str in base64, and decode it on javascript side.

  • Android

    String str = "xxx";
    //encode in base64
    String base64Str = Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
    myWebView.loadUrl("javascript:xxx('"+ base64Str +"')");
    
  • Javascript

    function xxx(val) {
        //decode from base64
        var str = atob(data)
    }
    
xfdai
  • 2,735
  • 1
  • 19
  • 18
  • I think encoding data as `JSON` rather than `base64` would be more effective (at least in terms of 6 bytes per char vs 8 bytes per char). Any `JSON` value is a valid javascript value, so that should work. – Klesun Nov 26 '19 at 18:48
1

Pass the paramter directly in the url

webView.loadUrl("file:///android_asset/animation.html?message=testing");

Get the paramter in html file

var url_string = window.location.href
var url = new URL(url_string);
var message= url.searchParams.get("message");
Levon Petrosyan
  • 8,815
  • 8
  • 54
  • 65
0

Solutions by Hungr would work, but using the same document they point out, I do the following:

in my Android code WebAppInterface class:

@JavascriptInterface
fun provideData(val input: String): String{
val output = ""
//some operation with input
    return output
}

then in host activity for webview:

webView.addJavascriptInterface(WebAppInterface(this), "Provider")

Inside your JS or HTML:

document.getElementbyId("Text").innerhtml = Provider.provideData(input);
Javad Arjmandi
  • 331
  • 1
  • 3
  • 12