Android WebView与Javascript交互
16lz
2021-01-23
WebView与Javascript交互是双向的数据传递:
(1)H5网页的JS函数调用Native函数
(2)Native函数调用JS函数
1、H5网页实现,主要实现actionFromNative()、actionFromNativeWithParam(String str),放在assets文件下文件名为 hybrid.html
<html><head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <script type="text/javascript"> function actionFromNativeWithParam(arg){ document.getElementById("log_msg").innerHTML += ("
+arg); } script>head><body><p>WebView与Javascript交互p><div> <button onClick="window.js2native.actionFromJsWithParam('come from Js')">调用Native代码button>div><br/><div id="log_msg">调用打印信息div>body>html>
2、Activity 中webview 设置看注释
public class MainActivity extends Activity { private WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = (WebView) findViewById(R.id.webview); // 启用javascript mWebView.getSettings().setJavaScriptEnabled(true); // 从assets目录下面的加载html mWebView.loadUrl("file:///android_asset/hybrid.html"); mWebView.addJavascriptInterface(new JsInterface(), "js2native"); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { mWebView.loadUrl("javascript:actionFromNativeWithParam(" + "'come from Native'" + ")"); } }); } final class JsInterface { @JavascriptInterface public void actionFromJsWithParam(final String str) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "js调用了Native函数:" + str, Toast.LENGTH_SHORT).show(); } }); } }}
mWebView.addJavascriptInterface(new JsInterface(), “js2native”);相当于添加一个js回调接口,然后给这个起一个别名, @android.webkit.JavascriptInterface为了解决addJavascriptInterface漏洞的,在4.2以后才有的。
js(HTML)访问Android(Java)端代码是通过jsObj对象实现的,调用jsObj对象中的函数,如: “window.js2native.actionFromJsWithParam(‘come from Js’)”,这里的js2native就是Native中JsInterface()对象的别名Android(Java)访问js(HTML)端代码是通过loadUrl函数实现的,访问格式如:mWebView.loadUrl(“javascript:actionFromNative()”);
3、布局文件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Native调用js函数"/>LinearLayout>
4、Demo 截图
更多相关文章
- android studio的Gradle一直在sync的办法,不停的下载各种文件
- Android Java和JavaScript代码相互调用
- android 音频系统java部分代码阅读
- Android 最终image文件的来源
- Android 常用代码集合
- Android 文件操作,删除,拷贝文件等
- Android系统源码编译全过程——下载Android源文件并编译
- [Android] 文件夹下文件的个数限制