JS與IOS、Android的互動

來源:互聯網
上載者:User

標籤:java   js代碼   http   ebs   span   github   方法   override   總結   

一、JS與Android

放在了assets檔案夾下了(注意若使用的是AS這個IDE,assets檔案夾應放在src/main目錄下)

<!DOCTYPE html><html>   <head>      <meta charset="utf-8">      <title>葛夫鋒</title>            <script>         function callAndroid(){            test.hello("js調用了android中的hello方法");         }      </script>   </head>   <body>      <button type="button" id="button1" onclick="callAndroid()">js調用android中的代碼</button>   </body></html>

代碼非常簡單,頁面中就一個按鈕,點擊這個按鈕調用callAndroid函數,這裡需注意callAndroid函數中的語句是android中對外的的一個函數,在android中的代碼:

{    ...       webSettings.setJavaScriptEnabled(true);    webView.addJavascriptInterface(this, "test");//對應js中的test.xxx    webView.loadUrl("file:///android_asset/js_web.html");}@JavascriptInterfacepublic void hello(String msg){//對應js中xxx.hello("")    Log.e("webview","hello");    Toast.makeText(this,msg,Toast.LENGTH_LONG).show();}

這裡需注意的是hello函數加上註解@javascriptInterface,這樣點擊html中的按鈕就會調用android中的hello方法了。

二、Android調用JS代碼

js代碼如下:

<script>   function callJS(){      alert("android調用了js中的callJS方法");   }</script>

android代碼如下:

public void click(View view){    webView.post(new Runnable() {        @Override        public void run() {            webView.loadUrl("javascript:callJS()");        }    });}

當android中的按鈕被點擊時會觸發click方法,然後執行webview.loadUrl("javascript:callJS()"),然後js中正好有callJS這個方法,然後alert()就會被執行。

這個總結很好:

https://github.com/shaojiankui/iOS-WebView-JavaScript

JS與IOS、Android的互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.