Android—WebView与JS交互
生活随笔
收集整理的這篇文章主要介紹了
Android—WebView与JS交互
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Html文件:
WebView與JS交互方式:
1. 前提:
WebSettings webSettings = webView.getSettings(); // 設置與Js交互的權限 webSettings.setJavaScriptEnabled(true);webView.setWebChromeClient(new WebChromeClient(){@Overridepublic boolean onJsAlert(WebView view, String url, String message, JsResult result) {AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this).setTitle(R.string.app_name).setMessage(message).setPositiveButton("ok", new AlertDialog.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {result.confirm();}});b2.setCancelable(false);b2.create();b2.show();return true;} });JS的彈框在WebView中需要通過重寫onJsAlert()、onJsConfirm()、onJsPrompt()方法實現,分別對應JS的警告框,確認框,輸入框。
webView還有一個setWebClient()方法,幫助處理各種通知、請求事件。
setWebChromeClient輔助WebView處理JavaScript的對話框,網站圖標,網站title,加載進度等
2. WebView調用JS的方法
(1) 通過WebView的loadUrl()
加載對應頁面
webView.loadUrl("file:/sdcard/WebView_Test.html"); webView.loadUrl("https://www.baidu.com/");調用JS中的callJS()方法
webView.loadUrl("javascript:callJS()");(2)?通過WebView的evaluateJavascript()
webView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {@Overridepublic void onReceiveValue(String value) {//此處為 js 返回的結果} });3. JS中調用Android方法
通過addJavascriptInterface()進行對象映射
public class JniUtil {static {System.loadLibrary("native_text");}@JavascriptInterfacepublic static native String helloWorld();@JavascriptInterfacepublic void hello(String msg) {System.out.println("JS調用了Android的hello方法");} }webView.addJavascriptInterface(new JniUtil(), "test");test是JniUtil對象,可以在JS中使用,在JS中調用test.hello()或者test.helloWorld()都可以看到對應結果,注意方法要加上對應注解。
總結
以上是生活随笔為你收集整理的Android—WebView与JS交互的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: INI 文件的操作
- 下一篇: Android—多版本主要适配内容