Android中的WebView組件與JavaScript交互

一、html中通過js調用java代碼

       javascript中調用java代碼其實就記住一點,webview設置一個和js交互的接口(注意這裏只是一般的意思,並不是java中接口的含義),這個接口其實是一個一般的類,同時爲這個接口取一個別名。這個過程如下:

mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

new DemoJavaScriptInterface就是這個接口,demo就是這個接口的別名。

上面的代碼執行之後在html的js中就能通過別名(這裏是“demo”)來調用newDemoJavaScriptInterface類中的任何方法。

如我們想讓html中的一個button點擊之後調用java中的函數可以這樣:

<input type="button"  value="click me"  onclick="window.demo.clickOnAndroid()"/>

但是因爲安全問題,在Android4.4中(如果應用的android:targetSdkVersion數值爲19+)JS只能訪問帶有 @JavascriptInterface註解的Java函數。因此如果你的開發版本比較高,需要在被調用的函數前加上@JavascriptInterface註解。

谷歌給出的代碼示例:

WebViewDemo.java

    package com.google.android.webviewdemo;
    import android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.util.Log;
    import android.webkit.JsResult;
    import android.webkit.WebChromeClient;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    /**
     * Demonstrates how to embed a WebView in your activity. Also demonstrates how
     * to have javascript in the WebView call into the activity, and how the activity
     * can invoke javascript.
     * <p>
     * In this example, clicking on the android in the WebView will result in a call into
     * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
     * will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
     * method.
     * <p>
     * Obviously all of this could have been accomplished without calling into the activity
     * and then back into javascript, but this code is intended to show how to set up the
     * code paths for this sort of communication.
     *
     */
    public class WebViewDemo extends Activity {
        private static final String LOG_TAG = "WebViewDemo";
        private WebView mWebView;
        private Handler mHandler = new Handler();
        @Override
        public void onCreate(Bundle icicle) {
            super.onCreate(icicle);
            setContentView(R.layout.main);
            mWebView = (WebView) findViewById(R.id.webview);
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setSavePassword(false);
            webSettings.setSaveFormData(false);
            webSettings.setJavaScriptEnabled(true);
            webSettings.setSupportZoom(false);
            mWebView.setWebChromeClient(new MyWebChromeClient());
            mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
            mWebView.loadUrl("file:///android_asset/demo.html");
        }
        final class DemoJavaScriptInterface {
            DemoJavaScriptInterface() {
            }
            /**
             * This is not called on the UI thread. Post a runnable to invoke
             * loadUrl on the UI thread.
             */
            public void clickOnAndroid() {
                mHandler.post(new Runnable() {
                    public void run() {
                        mWebView.loadUrl("javascript:wave()");
                    }
                });
            }
        }
        /**
         * Provides a hook for calling "alert" from javascript. Useful for
         * debugging your javascript.
         */
        final class MyWebChromeClient extends WebChromeClient {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.d(LOG_TAG, message);
                result.confirm();
                return true;
            }
        }
    }

demo.html

    <html>
        <script language="javascript">
            /* This function is invoked by the activity */
            function wave() {
                alert("1");
                document.getElementById("droid").src="android_waving.png";
                alert("2");
            }
        </script>
        <body>
            <!-- Calls into the javascript interface for the activity -->
            <a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
                margin:0px auto;
                padding:10px;
                text-align:center;
                border:2px solid #202020;" >
                    <img id="droid" src="android_normal.png"/><br>
                    Click me!
            </div></a>
        </body>
    </html>

main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/intro"
            android:padding="4dip"
            android:textSize="16sp"
            />

        <WebView
            android:id="@+id/webview"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            />

    </LinearLayout>

二、Android調用js

上面的代碼在演示如何在js中調用java代碼的同時也演示瞭如何在java中調用js

調用形式:

mWebView.loadUrl("javascript:wave()");

其中wave()是js中的一個方法,當然你可以把這個方法改成其他的方法,也就是android調用其他的方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章