
本篇文章给大家带来的内容是关于JavaScript交互的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Carson</title>
<script>
function callAndroid(){
test.hello("js调用了android中的hello方法");
}
function returnResult(){
alert("result is");
}
</script>
</head>
<body>
<button type="button" id="button1" onclick="callAndroid()"> 调用安卓代码 </button>
</body>
</html>
package com.example.webjs;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button tojs;
WebView webView;
@SuppressLint("JavascriptInterface")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.web_id);
tojs = findViewById(R.id.calljs_but_id);
WebSettings webSettings = webView.getSettings();
// 设置与Js交互的权限
webSettings.setJavaScriptEnabled(true);
// 设置允许JS弹窗
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//设置对象映射
webView.addJavascriptInterface(new JsToAndroid() , "test");
// 先载入JS代码
// 格式规定为:file:///android_asset/文件名.html
webView.loadUrl("file:///android_asset/text.html");
alteView(webView);
tojs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String result = "你好";
// webView.loadUrl("javascript:returnResult(" + result + ")");
webView.loadUrl("javascript:returnResult()");
}
});
}
public class JsToAndroid{
@JavascriptInterface
public void hello(final String str ){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this , str , Toast.LENGTH_LONG).show();
}
});
}
}
public void alteView(WebView webView){
// webView.setWebChromeClient(new WebChromeClient());
webView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
Log.e("tag" ,"执行次数");
AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
b.setTitle("Alert");
b.setMessage(message);
b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
b.setCancelable(false);
// b.create().show();
return super.onJsAlert(view, url, message, result);
}
});
}
}