我试图检测 webview 的 html 按钮点击进入 java 代码(在活动中)。
我通过Android WebView中的javascript引用了另一个SO
Detect click on HTML button
但不工作。我的代码:
索引.html
<html>
<head>
<script language="javascript">
function js1() {
document.loginform.method="post";
document.loginform.action = "https://example.com/chechlogin.asp";
}
</script>
</head>
<body>
<form name="loginform">
<input type="text" name="empcode" value="58686" /><br/>
<input type="password" name="emppassNTL" />
<input type="submit" name="submit" id="submit_id" onclick="login.performClick();" />
</form>
</body>
</html>
MainActivity.java
package com.example.webview;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
private EditText field;
private WebView browser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
field = (EditText)findViewById(R.id.urlField);
browser = (WebView)findViewById(R.id.webView1);
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebViewClient(new MyBrowser());
browser.loadUrl("file:///android_asset/index.html");
}
@SuppressLint("JavascriptInterface")
public void open(View view){
String url = field.getText().toString();
browser.getSettings().setLoadsImagesAutomatically(true);
browser.getSettings().setJavaScriptEnabled(true);
browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
browser.loadUrl(url);
browser.addJavascriptInterface(new Object()
{
@JavascriptInterface
public void performClick()
{
Log.d("LOGIN::", "Clicked");
Toast.makeText(MainActivity.this, "Login clicked", Toast.LENGTH_LONG).show();
}
}, "login");
}
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
但是没有调用 performClick() 方法。
请更正错误。