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.

1
  • WARNING: To those thinking loadUrl is the way to go, check out the answer with evaluateJavascript in it. It's easy to overlook. Commented Dec 3, 2019 at 9:00

6 Answers 6

59

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

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

11 Comments

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?
yes as long as the javascript function exists in your web page
I see that's why I will load the javascript because it has the code to pass some data.
please try and see if there is any problem;)
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.
|
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

5 Comments

very very nice .... onPageFinished is important point that i forgot to use that...
Where can I add the android_asset folder
Wow webview.loadUrl("javascript:init('" + theArgumentYouWantToPass + "')"); works great.
how to pass more than one value in it webview.loadUrl("javascript:init('" + theArgumentYouWantToPass + "')");
@AkshayNandwana webView.loadUrl("javascript:init('" + selectedItemName+","+price + "')"); in js function init(values) { var valuesArray=values.split(','); payment.items = valuesArray[0]; payment.amount = valuesArray[1];
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);
    }
}

1 Comment

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.
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)
    }
    

1 Comment

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.
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");

Comments

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);

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.