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?
As you can see, a function that’ll be called from JavaScript has the special annotation @JavascriptInterface, which indicates to WebView that this function can be called from JS. The next thing to do is to add this interface to WebView. Here we name it Android, but you can name it as you want.
Binding JavaScript to Android WebView allows you to bind JavaScript code to Android code through an interface. To do this, we must use the addJavaScriptInterface () method, which is passed the class that provides the interface for JS, and the name that will be used to display the instance in JS (for example, “ AndroidFunction “).
If the WebView has been destroyed, any call to the WebSettings method will raise an IllegalStateException. To use JavaScript, you need to enable it by calling the setJavaScriptEnabled () method on the WebSettings object. WebViewClient is called when page content is being rendered.
To use JavaScript, you need to enable it by calling the setJavaScriptEnabled () method on the WebSettings object. WebViewClient is called when page content is being rendered. You can also intercept the URL loading here (using the shouldOverrideUrlLoading () method).
webview.loadUrl("javascript:functionName(\"" + argument + "\")");
Change your line with this..
myWebView.loadUrl("javascript:testEcho('Hello World!')");
try this one might be helpful to you...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With