站長資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        在WebView中使用JavaScript的方法介紹

        在WebView中使用JavaScript的方法介紹

        如果你想要載入的頁面中用了JavaScript,你必須為你的WebView使能JavaScript。一旦使能之后,你也可以自己創(chuàng)建接口在你的應(yīng)用和JavaScript代碼間進(jìn)行交互。

        可以通過getSettings()獲得WebSettings,然后用setJavaScriptEnabled()使能JavaScript:

        WebView myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true);

        綁定JavaScript與Android代碼

        當(dāng)你為你的Android應(yīng)用中的WebView專門開發(fā)一個(gè)網(wǎng)頁應(yīng)用時(shí),你可以創(chuàng)建你的JavaScript代碼和你的客戶端的Android代碼之間的接口。

        比如,你可以用JavaScript代碼調(diào)用Android代碼中的方法,來展現(xiàn)一個(gè)對話框之類,而不是使用alert()方法(JS中的對話框方法)。

        在JS和Android代碼間綁定一個(gè)新的接口,需要調(diào)用 addJavascriptInterface()方法。

        方法參數(shù)傳入一個(gè)Java對象實(shí)例和一個(gè)字符串,該字符串是一個(gè)名字(interface name,注意此接口不是通常所說的那個(gè)用來實(shí)現(xiàn)的接口,而是傳入的這個(gè)對象在JS中的別名),在JS代碼中用此名字調(diào)用該Java對象的方法。

        注意這個(gè)方法可以讓JS代碼控制宿主程序,這是一個(gè)非常有力的特性,但是同時(shí)也存在一些安全問題,因?yàn)檫M(jìn)一步JS代碼可以通過反射訪問到注入對象的公有域。攻擊者可能會(huì)在HTML和JavaScript中包含了有威脅性的代碼。

        所以Android 4.1,API 17,也就是JELLY_BEAN 開始,只有被JavascriptInterface 注解標(biāo)識的公有方法可以被JS代碼訪問。

        另外,因?yàn)镴S代碼和Java對象在這個(gè)WebView所私有的后臺線程交互,所以還需要注意線程安全性問題。

        注意,與JS代碼綁定的的這個(gè)Java對象運(yùn)行在另一個(gè)線程中,與創(chuàng)建它的線程不是一個(gè)線程。

        注意,這個(gè)Java對象的域是不可訪問的。

        綁定JavaScript與Android代碼的例子

        比如可以定義這么一個(gè)類:

        /** * 自定義的Android代碼和JavaScript代碼之間的橋梁類      *       * @author 1      * */ public class WebAppInterface     {         Context mContext;          /** Instantiate the interface and set the context */          WebAppInterface(Context c)         {             mContext = c;         } /** Show a toast from the web page */          // 如果target 大于等于API 17,則需要加上如下注解          // @JavascriptInterface public void showToast(String toast)         {          // Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();           Toast.makeText(mContext, toast, Toast.LENGTH_LONG).show();         }     }

        然后將這個(gè)類和你的WebView中的JS代碼綁定:

        WebView webView = (WebView) findViewById(R.id.webview); webView.addJavascriptInterface(new WebAppInterface(this), "Android");

        給這個(gè)對象起的別名叫“Android”。

        這個(gè)就創(chuàng)立了一個(gè)接口名,叫“Android”,運(yùn)行在WebView中的JS代碼可以通過這個(gè)名字調(diào)用WebAppInterface類中的showToast()方法:

        <input type="button" value="Say hello"  onClick="showAndroidToast('Hello Android!')" />  <script type="text/javascript"> function showAndroidToast(toast)      {         Android.showToast(toast);     } </script>

        特別注意:需要設(shè)置chrome handler

        兩個(gè)問題:

        1、網(wǎng)頁按鈕按下后不出現(xiàn)JS對話框是因?yàn)闆]有設(shè)置chrome handler,需要設(shè)置如下: 

        // 如果不設(shè)置這個(gè),JS代碼中的按鈕會(huì)顯示,但是按下去卻不彈出對話框  // Sets the chrome handler. This is an implementation of WebChromeClient  // for use in handling JavaScript dialogs, favicons, titles, and the // progress. This will replace the current handler.  myWebView.setWebChromeClient(new WebChromeClient()         {              @Override public boolean onJsAlert(WebView view, String url,              String message,                     JsResult result)             { // TODO Auto-generated method stub return super.             onJsAlert(view, url, message, result);             }          });

        2.調(diào)用Android代碼的那個(gè)按鈕也沒有出現(xiàn)Toast是因?yàn)槲野褎e名寫錯(cuò)了(大小寫沒有注意)。

        Android調(diào)用JavaScript代碼

        這個(gè)還比較簡單,需要調(diào)用的時(shí)候只需要一行代碼:  

        myWebView.loadUrl("javascript:myFunction()");

        其中myFunction()是JS函數(shù)。

        這里要補(bǔ)充一下,如果JavaScript函數(shù)是帶參數(shù)的,那么調(diào)用時(shí)要特別注意。

        比如下面這個(gè)JS函數(shù),在原來內(nèi)容上加入一行:

        function writeLine(string)     {         console.log("Write a new Line");         //調(diào)試信息          document.getElementById("content").innerHTML += string +          "<br />";         //在content標(biāo)簽段落加入新行          }

        注:其中content是自定義的標(biāo)簽,html中有一個(gè)段落是:

        <p id="content"></p>

        那么在Android代碼中調(diào)用這個(gè)writeLine()函數(shù)時(shí),需要傳入一個(gè)字符串參數(shù),比如,想要傳入一個(gè)叫name的String:

        myWebView.loadUrl("javascript:writeLine('"+name+"')"); //JS代碼要是帶參數(shù)

        還有就是要注意雙引號中的函數(shù)名一定不要寫錯(cuò)。

        程序?qū)嵗?/strong>

        效果如下:

        在WebView中使用JavaScript的方法介紹

        界面中包含一個(gè)TextView,旁邊一個(gè)Button,下面整個(gè)是一個(gè)WebView。

        在WebView中載入了一個(gè)本地html文件,本地文件存放在assets文件夾中。

        網(wǎng)頁中前四個(gè)按鈕調(diào)用的是JavaScript函數(shù),顯示各種對話框。

        SayHello按鈕調(diào)用Android代碼中的一個(gè)方法,顯示一個(gè)Toast,如圖中所示。

        為了證明Android也可以調(diào)用JS代碼,最上方的Android Button按下后和“點(diǎn)擊這里”那個(gè)按鈕的效果一致,都是出現(xiàn)JS的對話框。

        Activity代碼:

        package com.example.hellowebjs;  import android.annotation.SuppressLint;  import android.app.Activity;  import android.content.Context;  import android.os.Bundle;  import android.view.View;  import android.webkit.JsResult;  import android.webkit.WebChromeClient;  import android.webkit.WebSettings;  import android.webkit.WebView;  import android.webkit.WebViewClient;  import android.widget.Button;  import android.widget.Toast;  public class WebJSActivity extends Activity { private WebView myWebView = null; private Button myButton = null;      @SuppressLint("SetJavaScriptEnabled")     @Override public void onCreate(Bundle savedInstanceState)     { super.onCreate(savedInstanceState);         setContentView(R.layout.activity_web_js);          myWebView = (WebView) findViewById(R.id.myWebView);          // 得到設(shè)置屬性的對象          WebSettings webSettings = myWebView.getSettings();          // 使能JavaScript          webSettings.setJavaScriptEnabled(true);          // 支持中文,否則頁面中中文顯示亂碼          webSettings.setDefaultTextEncodingName("GBK");           // 限制在WebView中打開網(wǎng)頁,而不用默認(rèn)瀏覽器           myWebView.setWebViewClient(new WebViewClient());           // 如果不設(shè)置這個(gè),JS代碼中的按鈕會(huì)顯示,但是按下去卻不彈出對話框           // Sets the chrome handler.           //This is an implementation of WebChromeClient           // for use in handling JavaScript dialogs, favicons,           //titles, and the           // progress. This will replace the current handler.           myWebView.setWebChromeClient(new WebChromeClient()         {           @Override public boolean onJsAlert(WebView view, String url,           String message,                     JsResult result)             { // TODO Auto-generated method stub return              super.onJsAlert(view, url, message, result);             }          });          // 用JavaScript調(diào)用Android函數(shù):          // 先建立橋梁類,將要調(diào)用的Android代碼寫入橋梁類的public函數(shù)          // 綁定橋梁類和WebView中運(yùn)行的JavaScript代碼           // 將一個(gè)對象起一個(gè)別名傳入,在JS代碼中用這個(gè)別名代替這個(gè)對象,          可以調(diào)用這個(gè)對象的一些方法           myWebView.addJavascriptInterface(new WebAppInterface(this),           "myInterfaceName");           // 載入頁面:本地html資源文件           myWebView.loadUrl("file:///android_asset/sample.html");           // 這里用一個(gè)Android按鈕按下后調(diào)用JS中的代碼           myButton = (Button) findViewById(R.id.button1);         myButton.setOnClickListener(new View.OnClickListener()         {              @Override public void onClick(View v)             {             // 用Android代碼調(diào)用JavaScript函數(shù):              myWebView.loadUrl("javascript:myFunction()");              // 這里實(shí)現(xiàn)的效果和在網(wǎng)頁中點(diǎn)擊第一個(gè)按鈕的效果一致  }         });      } /** * 自定義的Android代碼和JavaScript代碼之間的橋梁類      *       * @author 1      * */ public class WebAppInterface     {         Context mContext;          /** Instantiate the interface and set the context */          WebAppInterface(Context c)         {             mContext = c;         } /** Show a toast from the web page */          // 如果target 大于等于API 17,則需要加上如下注解          // @JavascriptInterface public void showToast(String toast)         { // Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();           Toast.makeText(mContext, toast, Toast.LENGTH_LONG).show();         }     }  }

        HTML文件:

        <html> <head> <h1> This is a HTML Page </h1>  <!-- JavaScript腳本,主要包括了按鈕要執(zhí)行的函數(shù),顯示對話框等 -->  <script type="text/javascript">  //JavaScript方法,彈出對話框顯示信息  function myFunction()     {         alert("Hello World!");     } function onAlert()     {         console.log("onAlert method");         //顯示調(diào)試信息   alert("This is a alert sample from html");     } function onConfirm()     {         console.log("onConfirm method");          var b = confirm("are you sure to login?");         alert("your choice is " + b);     } function onPrompt()     {         console.log("onPrompt method");          var b = prompt("please input your password", "aaa");         alert("your input is " + b);     } //調(diào)用綁定的Java對象的方法,即調(diào)用Android代碼顯示對話框    function showAndroidToast(toast)     {         console.log("showAndroidToast method");         myInterfaceName.showToast(toast);         //注意此處的myInterfaceName要和外部傳入的名字一致,大小寫正確           }           </script>           </head>           <body>           <p>           <!-- 前四個(gè)按鈕調(diào)用JS函數(shù) -->            JavaScript函數(shù)調(diào)用            <br />             <button onclick="myFunction()">點(diǎn)擊這里!</button>             <br />             <input type="button" value="alert" onclick="onAlert()" />             <br />             <input type="button" value="confirm" onclick="onConfirm()" />             <br />              <input type="button" value="prompt" onclick="onPrompt()" />             <br />              <!-- 上面用了兩種定義按鈕的方式,效果一樣的 -->               </p>                <p>                <!-- 這個(gè)Say hello 按鈕調(diào)用Android代碼中的方法 -->                用JavaScript按鈕調(diào)用Android代碼                <br />       <input type="button" value="Say hello"        onClick="showAndroidToast('Hello Android!')" />        </p>        <a href="http://www.google.com" />Google </a>        </body> </html>

        Activity布局文件:

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:id="@+id/myRelativeLayout"  android:layout_width="match_parent"  android:layout_height="match_parent" >  <TextView android:id="@+id/textView1"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:padding="@dimen/padding_medium"  android:text="@string/hello_world" tools:context=".WebJSActivity" />  <Button android:id="@+id/button1"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:layout_toRightOf="@id/textView1"  android:text="@string/btn1_text" />   <WebView android:id="@+id/myWebView"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:layout_below="@id/textView1" />    </RelativeLayout>

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
        主站蜘蛛池模板: 日韩人妻精品一区二区三区视频| 久久精品国产亚洲AV无码娇色| 亚欧无码精品无码有性视频| 九九热在线精品视频| 亚洲AV永久精品爱情岛论坛| 久久www免费人成精品香蕉| 亚洲精品你懂的| 97人妻无码一区二区精品免费| 亚洲精品国偷自产在线| 欧美成人精品欧美一级乱黄一区二区精品在线 | 欧美精品成人3d在线| 日本精品中文字幕| 91视频国产精品| 国产精品日韩AV在线播放| 欧美午夜精品久久久久免费视| 亚洲精品美女久久久久99小说| 91精品福利在线观看| 国产92成人精品视频免费| 精品久久久久久亚洲精品| 亚洲国产精品无码久久SM| 香蕉依依精品视频在线播放 | 亚洲精品国产成人片| 亚洲爆乳无码精品AAA片蜜桃| 精品视频一区二区三区| 国产免费久久精品丫丫| 精品国产污污免费网站入口| 国产精品免费久久| 午夜精品美女写真福利| 国产成人精品免费视频大| 99热日韩这里只有精品| 久久久国产精品福利免费| 精品无码国产污污污免费网站| 亚洲国产精品狼友中文久久久| 欧美日韩国产成人高清视频,欧美日韩在线精品一 | 99热热久久这里只有精品68 | 国产成人无码精品久久久久免费| 亚洲自偷自偷精品| 国产成人精品亚洲精品| 国产精品无码久久四虎| 国产精品亚洲专区无码WEB| 国产在线精品一区二区夜色|