WebView與JS之間的交互

WebView與JS之間的交互

WebView與JS之間的交互分幾步:

1.初始化WebView,開啓與JS的交互

2.加載html

3.雙方定義接口函數,約定接口標籤

4.互相調用


案例:

MainActivity.java

package com.meizivskai.haihang;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    private WebView mWebView;
    private TextView tvContent;
    private Button btnClick;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = (WebView) findViewById(R.id.web_view);

        //開啓與JS之間的交互
        mWebView.getSettings().setJavaScriptEnabled(true);

        // 從assets目錄下面的加載html
        mWebView.loadUrl("file:///android_asset/test.html");
        mWebView.addJavascriptInterface(this, "test");
        tvContent = (TextView) findViewById(R.id.tv_content);
        btnClick = (Button) findViewById(R.id.btn_click);

        btnClick.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 無參數調用
                mWebView.loadUrl("javascript:actionFromNative()");
                // 傳遞參數調用
                mWebView.loadUrl("javascript:actionFromNativeWithParam(" + "'come from Native'" + ")");
            }
        });
    }


    /**
     * 與JS之間定義的接口
     */
    @android.webkit.JavascriptInterface
    public void actionFromJs() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "js調用了Native函數", Toast.LENGTH_SHORT).show();
                String text = tvContent.getText() + "\njs調用了Native函數";
                tvContent.setText(text);
            }
        });
    }

    /**
     * 與JS之間定義的接口
     */
    @android.webkit.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();
                String text = tvContent.getText() + "\njs調用了Native函數傳遞參數:" + str;
                tvContent.setText(text);
            }
        });

    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.meizivskai.haihang.MainActivity">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Native調用js函數" />

</LinearLayout>

assets目錄下的test.html

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <script type="text/javascript">
    function actionFromNative(){
         document.getElementById("log_msg").innerHTML +=
             "<br\>Native調用了js函數";
    }

    function actionFromNativeWithParam(arg){
         document.getElementById("log_msg").innerHTML +=
             ("<br\>Native調用了js函數並傳遞參數:"+arg);
    }


    </script>
</head>
<body>
<p>WebView與Javascript交互</p>
<div>
    <button onClick="window.test.actionFromJs()">點擊調用Native代碼</button>
</div>
<br/>
<div>
    <button onClick="window.test.actionFromJsWithParam('come from Js')">點擊調用Native代碼並傳遞參數</button>
</div>
<br/>
<div id="log_msg">調用打印信息</div>
</body>
</html>


PS:希望可以幫助大家。。。

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