我正在尝试从Java android代码调用javascript函数。我试图查看有关此问题的所有先前问题,但似乎无济于事。有什么建议吗?谢谢!
javascript code:
<html>
<head>
<script language="javascript">
function doSomething() {
alert('hey!!!!!!!');
}
</script>
</head>
<body>
ilana
</body>
</html>
java code (from an activity on create)
final WebView webview=(WebView)findViewById(R.id.myWebView);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new JavaScriptInterface(this), "Android");
webview.loadUrl("file:///android_asset/www/index.html");
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("javascript:doSomething()");
我更新的(但仍无法正常工作)代码是:
javascript:
<html>
<head>
<script type="text/javascript">
function doSomething(){
alert("hello");
}
</script>
</head>
<body>
hello hello hello!
</body>
</html>
java:
final WebView webview=(WebView)findViewById(R.id.myWebView);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/www/index.html");
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:doSomething()");
}
});
最佳答案
我认为您必须等待加载页面的结尾
试试看
webview.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:doSomething()");
}
});
Main在哪里。此活动的变化
webview.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result){
new AlertDialog.Builder(Main.this)
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK",
new AlertDialog.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
});
@ 注释 @
我的onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webview = (WebView)findViewById(R.id.webView1);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("", "!!!! here 1 !!!!");
view.loadUrl("javascript:doSomething()");
}
});
webview.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result){
Log.d("", "!!!! here 2 !!!!");
new AlertDialog.Builder(Main.this)
.setTitle("Alert")
.setMessage(message)
.setPositiveButton("OK",
new AlertDialog.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
});
webview.loadUrl("file:///android_asset/index.html");