1、Android原生需要在方法前加入“@JavascriptInterface”注解,原因在Android4.2以后,为了安全问题
@SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
@Override
protected void onCreate() {
super.onCreate();
binding.webView2.loadUrl("file:///android_asset/webview.html");
binding.webView2.addJavascriptInterface(new FromJs(),"testJs");
binding.webView2.getSettings().setJavaScriptEnabled(true);
}
public class FromJs{
@JavascriptInterface
public void toast(){
Toast.makeText(getActivity(),"执行",Toast.LENGTH_SHORT).show();
}
}
2、HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="button" onclick="test()"> 调用原生组件 </button>
<script>
function test() {
window.testJs.toast()
}
</script>
</body>
</html>