13

I have an activity with WebView and Button on it. Android sdk 17. Website isn't mine, so I can't change it anyway. I need to do js code by android button click.

I'm trying to do this

public class RostelecomLoginActivity extends Activity {

WebView webView;
String url;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rostelecom_login);

    Intent webIntent = getIntent();
    final String url = webIntent.getStringExtra("url");

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setSaveFormData(true);
    webView.getSettings().setSavePassword(true);

    Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            webView.addJavascriptInterface(new Object(){
                @JavascriptInterface
                public void test(){
                    Log.d("JS", "test");
                }
            },"Android");
            webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
        }
    });

    webView.loadUrl(url);

}}

But it doesn't do anything. How can I call my js right?

Cœur
  • 32,421
  • 21
  • 173
  • 232
Valeriy
  • 735
  • 2
  • 10
  • 27

3 Answers3

15
webview.loadUrl("javascript:functionName(\"" + argument + "\")");
Pratik Butani
  • 51,868
  • 51
  • 228
  • 375
12

Change your line with this..

myWebView.loadUrl("javascript:testEcho('Hello World!')");

try this one might be helpful to you...

Jibяaᴎ Khaᴎ
  • 3,118
  • 4
  • 32
  • 47
Vasu
  • 836
  • 2
  • 11
  • 27
1

I assume that you are trying to call the test function when you click on the external website you are accessing.

The way to call the functions you have defined on the Java-side is by the name you assigned when you created the javascript interface, in your case "Android"

So the call will be "window.Android.test()"

Also you have to wait to load the website and then inject the javascript code.

Check out the answer I did some weeks ago with code Hide WebView until JavaScript is done. It's a similar approach to manage the JS and Java using a webview.

Consider start doing a simple test when the page loads, and later add it inside the javascript click function.

Community
  • 1
  • 1
AlexBcn
  • 2,400
  • 2
  • 14
  • 28