webview跟javascript交互

android使用html5作布局文件http://www.cnblogs.com/andgoo/archive/2011/10/11/2207936.html

Android中webview跟JAVASCRIPT中的交互http://www.oschina.net/question/4873_27156

android软件开发之webView.addJavascriptInterface循环渐进【一】:http://www.sollyu.com/android-software-development-webview-addjavascriptinterface-cycle-of-gradual-one

android软件开发之webView.addJavascriptInterface循环渐进【二】:http://www.sollyu.com/586

WebView注入Java对象注意事项

在android4.2以前,注入步骤如下:

webview.getSetting().setJavaScriptEnable(true);  
class JsObject {  
    public String toString() { return "injectedObject"; }  
 }  
 webView.addJavascriptInterface(new JsObject(), "injectedObject");

Android4.2及以后,注入步骤如下:

webview.getSetting().setJavaScriptEnable(true);  
class JsObject {  
    @JavascriptInterface  
    public String toString() { return "injectedObject"; }  
 }  
 webView.addJavascriptInterface(new JsObject(), "injectedObject");
 

发现区别没?4.2之前向webview注入的对象所暴露的接口toString没有注释语句@JavascriptInterface,而4.2及以后的则多了注释语句@JavascriptInterface

经过查官方文档所知,因为这个接口允许JavaScript控制宿主应用程序,这是个很强大的特性,但同时,在4.2的版本前存在重大安全隐患,因为JavaScript可以使用反射访问注入webview的java对象的publicfields,在一个包含不信任内容的WebView中使用这个方法,会允许攻击者去篡改宿主应用程序,使用宿主应用程序的权限执行java代码。因此4.2以后,任何为JS暴露的接口,都需要加@JavascriptInterface,注释,这样,这个Java对象的fields将不允许被JS访问。

HTML调用android的方法:

1.配置android支持js

WebSettingswebSettings=webview.getSettings();

webSettings.setJavaScriptEnabled(true);//启用javascript支持

2.定义和暴露接口给js

webview.addJavascriptInterface(new PersonPlugin(), "Person");
private final class PersonPlugin {
        @JavascriptInterface
        public void getPersonList() {
            ......
        }
    }

3.js访问

Person.getPersonList();

Android访问HTML方法

1.在html定义方法

function show(){
  document.write("This is a test message.");
}

2.在android中访问js方法:

webview.loadUrl("javascript:show('" + JSONStr + "')");

例子:

================================================

package com.example.html5Java;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.*;
import com.example.html5Java.app.Person;
import com.example.html5Java.app.PersonService;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

public class MyActivity extends Activity {
    private static final String LOG_TAG = "WebViewDemo";
    private PersonService service;
    private WebView webview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        service = new PersonService();
        webview = (WebView) this.findViewById(R.id.webView);//android内置浏览器对象

        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);//启用javascript支持

        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setSupportZoom(false);
        webview.setWebChromeClient(new MyWebChromeClient());

        //添加一个js交互接口,方便html布局文件中的javascript代码能与后台java代码直接交互访问
        webview.addJavascriptInterface(new PersonPlugin(), "Person");//new类名,交互访问时使用的别名
        // <body onload="javascript:Person.getPersonList()">
        //其实可以把这个html布局文件放在公网中,这样方便随时更新维护  例如 webview.loadUrl("www.xxxx.com/index.html");
        webview.loadUrl("file:///android_asset/index.html");//加载本地的html布局文件

        webview.setWebViewClient(new WebViewClient() {
            //网页加载开始时调用,显示加载提示旋转进度条
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
            }

            //网页加载完成时调用,隐藏加载提示旋转进度条
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
            }

            //网页加载失败时调用,隐藏加载提示旋转进度条
            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

        });
    }

    //定义一个内部类,从java后台(可能是从网络,文件或者sqllite数据库) 获取List集合数据,并转换成json字符串,调用前台js代码
    private final class PersonPlugin {
        @JavascriptInterface
        public void getPersonList() {
            List<Person> list = service.getPersonList();//获得List数据集合
            //将List泛型集合的数据转换为JSON数据格式
            try {
                JSONArray arr = new JSONArray();
                for (Person person : list) {
                    JSONObject json = new JSONObject();
                    json.put("id", person.getId());
                    json.put("name", person.getName());
                    json.put("mobile", person.getMobile());
                    arr.put(json);

                }
                String JSONStr = arr.toString();//转换成json字符串
                webview.loadUrl("javascript:show('" + JSONStr + "')");//执行html布局文件中的javascript函数代码--
                Log.i("MainActivity", JSONStr);
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        @JavascriptInterface
        //打电话的方法
        public void call(String mobile) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile));
            startActivity(intent);
        }
    }

    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;
        }
    }
}
package com.dazhuo.domain;

public class Person {
    private Integer id;
    public Integer getId() {
        return id;
    }
    public Person(Integer id, String name, String mobile) {
        super();
        this.id = id;
        this.name = name;
        this.mobile = mobile;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    private String name;
    private String mobile;
}
package com.dazhuo.service;

import java.util.ArrayList;
import java.util.List;

import com.dazhuo.domain.Person;

public class PersonService {
   public List<Person> getPersonList()
   {
       
       List<Person> list =new ArrayList<Person>();
       list.add(new Person(32, "aa", "13675574545"));
       list.add(new Person(32, "bb", "13698874545"));
       list.add(new Person(32, "cc", "13644464545"));
       list.add(new Person(32, "dd", "13908978877"));
       list.add(new Person(32, "ee", "15908989898"));
     return list;
   }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript">
        function show(jsondata){
            var jsonobjs = eval(jsondata);
            var table = document.getElementById("personTable");
            for(var y=0; y<jsonobjs.length; y++){
                var tr = table.insertRow(table.rows.length); //添加一行
                //添加三列
                var td1 = tr.insertCell(0);
                var td2 = tr.insertCell(1);
                td2.align = "center";
                var td3 = tr.insertCell(2);
                td3.align = "center";
                //设置列内容和属性
                td1.innerHTML = jsonobjs[y].id;
                td2.innerHTML = jsonobjs[y].name;
                td3.innerHTML = "<a href='javascript:Person.call(\""+ jsonobjs[y].mobile+ "\")'>"+ jsonobjs[y].mobile+ "</a>";
            }
        }
        function test(){
            alert("======================>Alert测试");
            document.write("执行测试");
        }
    </script>

</head>
<!-- js代码通过webView调用其插件中的java代码 -->
<body onload="Person.getPersonList();">
<table border="0" width="100%" id="personTable" cellspacing="0">
    <tr>
        <td width="20%">编号</td><td width="40%" align="center">姓名</td><td align="center">电话</td>
    </tr>
</table>
<a href="javascript:window.location.reload();">刷新本页面</a>
<a href="javascript:test()">测试函数</a>
</body>

/</html>

转自:http://blog.csdn.net/dinglang_2009/article/details/6862627

相关推荐