WebView加載html與JS交互

一、加載Html的幾種方法

  1. 直接在Activity中實例化WebView

    WebView webview =new WebView(this);
    webview.loadUrl(......);

  2. 在XML中生命webview
    WebView webView = (WebView) findViewById(R.id.webview);

  3. 載入工程內部頁面 page.html存儲在工程文件的assets根目錄下

     webView = (WebView) findViewById(R.id.webview);  
     webView.loadUrl("file:///file:///android_asset/page.html"); 
    

二、加載頁面時幾種簡單API使用

  • 設置縮放

       mWebView.getSettings().setBuiltInZoomControls(true); 
    
  • 在webview添加對js的支持

      setting.setJavaScriptEnabled(true);//支持js
    
  • 添加對中文支持

      setting.setDefaultTextEncodingName("GBK");//設置字符編碼  
    
  • 設置頁面滾動條風格

      webView.setScrollBarStyle(0);//滾動條風格,為0指滾動條不占用空間,直接覆蓋在網頁上
    
      取消滾動條
          this.setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
    
  • listview,webview中滾動拖動到頂部或者底部時的陰影(滑動到項部或底部不固定)

       WebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    

三、瀏覽器優化操作處理:

  1. WebView默認用系統自帶瀏覽器處理頁面跳轉。為了讓頁面跳轉在當前WebView中進行,

    重寫WebViewClient

    mWebView.setWebViewClient(new WebViewClient() {  
        @Override  
        public boolean shouldOverrideUrlLoading(WebView view, String url) {  
            view.loadUrl(url);//使用當前WebView處理跳轉  
            return true;//true表示此事件在此處被處理,不需要再廣播  
        }  
        @Override  
        public void onPageStarted(WebView view, String url, Bitmap favicon) {  
            //有頁面跳轉時被回調  
        }  
        @Override  
        public void onPageFinished(WebView view, String url) {  
            //頁面跳轉結束后被回調  
        }  
        @Override  
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {  
            Toast.makeText(WebViewDemo.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();  
        }  
    }); 
  1. 當WebView內容影響UI時調用WebChromeClient的方法

     mWebView.setWebChromeClient(new WebChromeClient() {  
        /** 
         * 處理JavaScript Alert事件 
         */  
        @Override  
        public boolean onJsAlert(WebView view, String url,  
                String message, final JsResult result) {  
            //用Android組件替換  
            new AlertDialog.Builder(WebViewDemo.this)  
                .setTitle("JS提示")  
                .setMessage(message)  
                .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int which) {  
                        result.confirm();  
                    }  
                })  
                .setCancelable(false)  
                .create().show();  
            return true;  
        }  
    });   
    
  2. 按BACK鍵時,不會返回跳轉前的頁面,而是退出本Activity,重寫onKeyDown()方法來解決此問題

     @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        //處理WebView跳轉返回  
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {  
            mWebView.goBack();  
            return true;  
        }  
        return super.onKeyDown(keyCode, event);  
    }  
      
    private class JsToJava {  
        public void jsMethod(String paramFromJS) {  
            Log.i("CDH", paramFromJS);  
        }  
    } 
    

四、WebView與JS交互

  • 總綱

           /* 
                            綁定Java對象到WebView,這樣可以讓JS與Java通信(JS訪問Java方法) 
                            第一個參數是自定義類對象,映射成JS對象 
                            第二個參數是第一個參數的JS別名 
                            調用示例: 
              mWebView.loadUrl("javascript:window.stub.jsMethod('param')"); 
           */  
          mWebView.addJavascriptInterface(new JsToJava(), "stub");  
            
          final EditText mEditText = (EditText)findViewById(R.id.web_view_text);  
    
          findViewById(R.id.web_view_search).setOnClickListener(new OnClickListener() {  
              @Override  
              public void onClick(View view) {  
                  String url = mEditText.getText().toString();  
                  if (url == null || "".equals(url)) {  
                      Toast.makeText(WebViewDemo.this, "請輸入URL", Toast.LENGTH_SHORT).show();  
                  } else {  
                      if (!url.startsWith("http:") && !url.startsWith("file:")) {  
                          url = "http://" + url;  
                      }  
                      mWebView.loadUrl(url);  
                  }  
              }  
          });  
          //默認頁面  
          mWebView.loadUrl("file:///android_asset/js_interact_demo.html");  
      }  
    
  • 撲捉加載頁面JS的過程

    • 注意到webview提供的兩個方法:

    • setWebChromeClient方法正是可以處理progress的加載,此外,還可以處理js對話框,在webview中顯示icon圖標等。

    • 對于setWebViewClient方法,一般用來處理html的加載(需要重載onPageStarted(WebView view, String url, Bitmap favicon))、關閉(需要重載onPageFinished(WebViewview, String url)方法)。

        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {// 載入進度改變而觸發
                    if (progress == 100) {
                            handler.sendEmptyMessage(1);// 如果全部載入,隱藏進度對話框
                    }
                        super.onProgressChanged(view, progress);
                }
        });
  • 獲取java中的數據:單獨構建一個接口,作為處理js與java的數據交互的橋梁

      封裝的代碼AndroidToastForJs.java
      
      public class AndroidToastForJs {
              
              private Context mContext;
          
          public AndroidToastForJs(Context context){
                  this.mContext = context;
              }
              
          //webview中調用toast原生組件
          public void showToast(String toast) {
                  Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
              }
              
          //webview中求和
          public int sum(int a,int b){
                  return a+b;
              }
              
           //以json實現webview與js之間的數據交互
          public String jsontohtml(){
                  JSONObject map;
                  JSONArray array = new JSONArray();
                  try {
                      map = new JSONObject();
                      map.put("name","aaron");
                      map.put("age", 25);
                      map.put("address", "中國上海");
                      array.put(map);
                      
                      map = new JSONObject();
                      map.put("name","jacky");
                      map.put("age", 22);
                      map.put("address", "中國北京");
                      array.put(map);
                      
                      map = new JSONObject();
                      map.put("name","vans");
                      map.put("age", 26);
                      map.put("address", "中國深圳");
                      map.put("phone","13888888888");
                      array.put(map);
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
                  return array.toString();
              }
          }
    

Webview提供的傳入js的方法:

webView.addJavascriptInterface(new AndroidToastForJs(mContext), "JavaScriptInterface");

Html頁面jsonData.html設計的部分代碼如下

    <script type="text/javascript">
        var result = JavaScriptInterface.jsontohtml();
        var obj = eval("("+result+")");//解析json字符串
        function showAndroidToast(toast) 
        {        
            JavaScriptInterface.showToast(toast); 
        }
        function getjsonData(){
            var result = JavaScriptInterface.jsontohtml();
            var obj = eval("("+result+")");//解析json字符串
            for(i=0;i<obj.length;i++){
                var user=obj[i];
                document.write("<p>姓名:"+user.name+"</p>");
                document.write("<p>年齡:"+user.age+"</p>");
                document.write("<p>地址:"+user.address+"</p>");
                if(user.phone!=null){
                    document.write("<p>手機號碼:"+user.address+"</p>");
                }
            }
        }   
        function list(){
            document.write("<div data-role='header'><p>another</p></div>");
        }
        </script>
    </head> 
    <body> 
    <div data-role="page" >
        <div data-role="header" data-theme="c">
            <h1>Android via Interface</h1>
        </div><!-- /header -->
        <div data-role="content">   
            <button value="say hello" onclick="showAndroidToast('Hello,Android!')" data-theme="e"></button>
            <button value="get json data" onclick="getjsonData()" data-theme="e"></button>  
        </div><!-- /content -->
    <div data-role="collapsible" data-theme="c" data-content-theme="f">
       <h3>I'm <script>document.write(obj[0].name);</script>,click to see my info</h3>
       <p><script>document.write("<p>姓名:"+obj[0].name+"</p>");</script></p>
       <p><script>document.write("<p>年齡:"+obj[0].age+"</p>");</script></p>
       <p><script>document.write("<p>地址:"+obj[0].address+"</p>");</script></p>
    </div>
        <div data-role="footer" data-theme="c">
            <h4>Page Footer</h4>
        </div><!-- /footer -->
    </div><!-- /page -->
    </body>

問題解決:

  1. 多圖片網頁手機加載數度慢

     1. 建議先用 webView.getSettings().setBlockNetworkImage(true); 將圖片下載阻塞
     2. 在瀏覽器的OnPageFinished事件中設置 webView.getSettings().setBlockNetworkImage(false); 
         通過圖片的延遲載入,讓網頁能更快地顯示
    

HTML5交互:

HTML5本地存儲在Android中的應用

  • HTML5提供了2種客戶端存儲數據新方法:

    1. localStorage 沒有時間限制

    2. sessionStorage 針對一個Session的數據存儲

       <script type="text/javascript"> 
           localStorage.lastname="Smith"; 
           document.write(localStorage.lastname); 
       </script> 
       <script type="text/javascript"> 
           sessionStorage.lastname="Smith"; 
           document.write(sessionStorage.lastname);
       </script> 
      

WebStorage的API:

//清空storage
localStorage.clear();

//設置一個鍵值
localStorage.setItem(“yarin”,“yangfegnsheng”);

//獲取一個鍵值
localStorage.getItem(“yarin”); 

//獲取指定下標的鍵的名稱(如同Array)
localStorage.key(0); 

//return “fresh” //刪除一個鍵值
localStorage.removeItem(“yarin”);

注意一定要在設置中開啟哦
setDomStorageEnabled(true)

在Android中進行操作:

//啟用數據庫
webSettings.setDatabaseEnabled(true);  
String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
//設置數據庫路徑
webSettings.setDatabasePath(dir);
//使用localStorage則必須打開
webSettings.setDomStorageEnabled(true);
//擴充數據庫的容量(在WebChromeClinet中實現)
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, 
        long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
    quotaUpdater.updateQuota(estimatedSize * 2);
}   

在JS中按常規進行數據庫操作:

tHandler, errorHandler);
        }
    );  
}
function dataSelectHandler(transaction, results){
    // Handle the results
    for (var i=0; i<results.rows.length; i++) {
        var row = results.rows.item(i);
        var newFeature = new Object();
        newFeature.name   = row['name'];
        newFeature.decs = row['desc'];
        
        document.getElementById("name").innerHTML="name:"+newFeature.name;
        document.getElementById("desc").innerHTML="desc:"+newFeature.decs;
    }
}
function updateData(){
    YARINDB.transaction(
        function (transaction) {
            var data = ['fengsheng yang','I am fengsheng']; 
            transaction.executeSql("UPDATE yarin SET name=?, desc=? WHERE id = 1", [data[0], data[1]]);
        }
    );  
    selectAll();
}
function ddeleteTables(){
    YARINDB.transaction(
        function (transaction) {
            transaction.executeSql("DROP TABLE yarin;", [], nullDataHandler, errorHandler);
        }
    );
    console.log("Table 'page_settings' has been dropped.");
}
注意onLoad中的初始化工作
function initLocalStorage(){
    if (window.localStorage) {
        textarea.addEventListener("keyup", function() {
            window.localStorage["value"] = this.value;
            window.localStorage["time"] = new Date().getTime();
        }, false);
    } else {
        alert("LocalStorage are not supported in this browser.");
    }
}

window.onload = function() {
    initDatabase();
    initLocalStorage();
}

HTML5地理位置服務在Android中的應用:

Android中:

    //啟用地理定位
webSettings.setGeolocationEnabled(true);
//設置定位的數據庫路徑
webSettings.setGeolocationDatabasePath(dir);
//配置權限(同樣在WebChromeClient中實現)
public void onGeolocationPermissionsShowPrompt(String origin, 
               GeolocationPermissions.Callback callback) {
    callback.invoke(origin, true, false);
    super.onGeolocationPermissionsShowPrompt(origin, callback);
}

在Manifest中添加權限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

HTML5中 通過navigator.geolocation對象獲取地理位置信息:

常用的navigator.geolocation對象有以下三種方法:

  1. //獲取當前地理位置

     navigator.geolocation.getCurrentPosition(success_callback_function, error_callback_function, position_options)
    
  2. //持續獲取地理位置

     navigator.geolocation.watchPosition(success_callback_function, error_callback_function, position_options)
    
  3. 清除持續獲取地理位置事件

     navigator.geolocation.clearWatch(watch_position_id)
    

----其中success_callback_function為成功之后處理的函數,error_callback_function為失敗之后返回的處理函數,參數position_options是配置項

在JS中的代碼:

//定位
function get_location() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(show_map,handle_error,{enableHighAccuracy:false,maximumAge:1000,timeout:15000});
    } else {
        alert("Your browser does not support HTML5 geoLocation");
    }
}
    
function show_map(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    var city = position.coords.city;
    //telnet localhost 5554
    //geo fix -82.411629 28.054553
    //geo fix -121.45356 46.51119 4392
    //geo nmea $GPGGA,001431.092,0118.2653,N,10351.1359,E,0,00,,-19.6,M,4.1,M,,0000*5B
    document.getElementById("Latitude").innerHTML="latitude:"+latitude;
    document.getElementById("Longitude").innerHTML="longitude:"+longitude;
    document.getElementById("City").innerHTML="city:"+city;
}
    
function handle_error(err) {
    switch (err.code) {
    case 1:
        alert("permission denied");
        break;
    case 2:
        alert("the network is down or the position satellites can't be contacted");
        break;
    case 3:
        alert("time out");
        break;
    default:
        alert("unknown error");
        break;
    }
}

----其中position對象包含很多數據 error代碼及選項 可以查看文檔

構建HTML5離線應用:

需要提供一個cache manifest文件,理出所有需要在離線狀態下使用的資源
例如:

CACHE MANIFEST 
#這是注釋
images/sound-icon.png
images/background.png
clock.html 
clock.css 
clock.js  

NETWORK: 
test.cgi
CACHE: 
style/default.css
FALLBACK: 
/files/projects /projects


在html標簽中聲明 <html manifest="clock.manifest">?

HTML5離線應用更新緩存機制

分為手動更新和自動更新2種

自動更新:

在cache manifest文件本身發生變化時更新緩存 資源文件發生變化不會觸發更新

手動更新:

使用window.applicationCache

    if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
        window.applicationCache.update();
    } 

在線狀態檢測

HTML5 提供了兩種檢測是否在線的方式:navigator.online(true/false) 和 online/offline事件。

在Android中構建離線應用:

//開啟應用程序緩存
webSettingssetAppCacheEnabled(true);
String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
//設置應用緩存的路徑
webSettings.setAppCachePath(dir);
//設置緩存的模式
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//設置應用緩存的最大尺寸
webSettings.setAppCacheMaxSize(1024*1024*8);
//擴充緩存的容量
public void onReachedMaxAppCacheSize(long spaceNeeded,
            long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
    quotaUpdater.updateQuota(spaceNeeded * 2);
}

Android與JS之間的互相調用

在JS中調用Android的函數方法

    final class InJavaScript {
    public void runOnAndroidJavaScript(final String str) {
        handler.post(new Runnable() {
            public void run() { 
                TextView show = (TextView) findViewById(R.id.textview);
                show.setText(str);
            }
        });
    }
}

//把本類的一個實例添加到js的全局對象window中,
//這樣就可以使用window.injs來調用它的方法
webView.addJavascriptInterface(new InJavaScript(), "injs");

在JavaScript中調用:

function sendToAndroid(){
    var str = "Cookie call the Android method from js";
    window.injs.runOnAndroidJavaScript(str);//調用android的函數
}

在Android中調用JS的方法:

在JS中的方法:

function getFromAndroid(str){
    document.getElementById("android").innerHTML=str;
}

在Android調用該方法:

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        //調用javascript中的方法
        webView.loadUrl("javascript:getFromAndroid('Cookie call the js function from Android')");
    }
});

Android中處理JS的警告,對話框等

在Android中處理JS的警告,對話框等需要對WebView設置WebChromeClient對象:

    //設置WebChromeClient
webView.setWebChromeClient(new WebChromeClient(){
    //處理javascript中的alert
    public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
        //構建一個Builder來顯示網頁中的對話框
        Builder builder = new Builder(MainActivity.this);
        builder.setTitle("Alert");
        builder.setMessage(message);
        builder.setPositiveButton(android.R.string.ok,
            new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
        builder.setCancelable(false);
        builder.create();
        builder.show();
        return true;
    };
    //處理javascript中的confirm
    public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
        Builder builder = new Builder(MainActivity.this);
        builder.setTitle("confirm");
        builder.setMessage(message);
        builder.setPositiveButton(android.R.string.ok,
            new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.confirm();
                }
            });
        builder.setNegativeButton(android.R.string.cancel,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    result.cancel();
                }
            });
        builder.setCancelable(false);
        builder.create();
        builder.show();
        return true;
    };
        
    @Override
    //設置網頁加載的進度條
    public void onProgressChanged(WebView view, int newProgress) {
        MainActivity.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress * 100);
        super.onProgressChanged(view, newProgress);
    }
    //設置應用程序的標題title
    public void onReceivedTitle(WebView view, String title) {
        MainActivity.this.setTitle(title);
        super.onReceivedTitle(view, title);
    }
});

Android中的調試:

通過JS代碼輸出log信息:

Js代碼: console.log("Hello World");
Log信息: Console: Hello World http://www.example.com/hello.html :82

在WebChromeClient中實現onConsoleMesaage()回調方法,讓其在LogCat中打印信息:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
    public void onConsoleMessage(String message, int lineNumber, String sourceID) {
        Log.d("MyApplication", message + " -- From line "
            + lineNumber + " of "
            + sourceID);
    }
});

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d("MyApplication", cm.message() + " -- From line "
            + cm.lineNumber() + " of "
            + cm.sourceId() );
        return true;
    }
});

---ConsoleMessage 還包括一個 MessageLevel 表示控制臺傳遞信息類型。

您可以用messageLevel()查詢信息級別,以確定信息的嚴重程度,然后使用適當的Log方法或采取其他適當的措施。

后面的內容在下篇中繼續

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 一、js和Android調用的前提 在講js和Android的互調之前,我們要先設置好webview的一些基本配置...
    Hawkinswang閱讀 7,923評論 0 14
  • 一、WebView 谷歌提供的系統組件,用來加載和展現html網頁,其采用webkit內核驅動,來實現網頁瀏覽功能...
    閑庭閱讀 7,042評論 2 12
  • JSBridge 1. Why do we need JSBridge? 2. Why is “JS”Bridge...
    loveqin閱讀 9,245評論 0 7
  • 你怎得兩面? 我面前你這般, 他面前你那般; 色蜥蜴樣地萬化,可覺累? 忌憚與我時被他窺見, 你可是孫悟空,會得七...
    Santa_Maria閱讀 205評論 0 2
  • 當我帶著我的床鋪再一次踏入這所我已經待了四年的高中時,突然發現這一幕和歷史驚人的相似。 我轉過頭對我爹說:"咱們怎...
    lemonzx閱讀 311評論 1 2