Android—WebView与JS交互
Html文件:
WebView與JS交互方式:
1. 前提:
WebSettings webSettings = webView.getSettings(); // 設(shè)置與Js交互的權(quán)限 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()方法實(shí)現(xiàn),分別對(duì)應(yīng)JS的警告框,確認(rèn)框,輸入框。
webView還有一個(gè)setWebClient()方法,幫助處理各種通知、請(qǐng)求事件。
setWebChromeClient輔助WebView處理JavaScript的對(duì)話框,網(wǎng)站圖標(biāo),網(wǎng)站title,加載進(jìn)度等
2. WebView調(diào)用JS的方法
(1) 通過WebView的loadUrl()
加載對(duì)應(yīng)頁面
webView.loadUrl("file:/sdcard/WebView_Test.html"); webView.loadUrl("https://www.baidu.com/");調(diào)用JS中的callJS()方法
webView.loadUrl("javascript:callJS()");(2)?通過WebView的evaluateJavascript()
webView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {@Overridepublic void onReceiveValue(String value) {//此處為 js 返回的結(jié)果} });3. JS中調(diào)用Android方法
通過addJavascriptInterface()進(jìn)行對(duì)象映射
public class JniUtil {static {System.loadLibrary("native_text");}@JavascriptInterfacepublic static native String helloWorld();@JavascriptInterfacepublic void hello(String msg) {System.out.println("JS調(diào)用了Android的hello方法");} }webView.addJavascriptInterface(new JniUtil(), "test");test是JniUtil對(duì)象,可以在JS中使用,在JS中調(diào)用test.hello()或者test.helloWorld()都可以看到對(duì)應(yīng)結(jié)果,注意方法要加上對(duì)應(yīng)注解。
總結(jié)
以上是生活随笔為你收集整理的Android—WebView与JS交互的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: INI 文件的操作
- 下一篇: android sina oauth2.