android 中java和javascript互動

來源:互聯網
上載者:User

標籤:

android的WebView是一個非常強大的控制項,本文主要針對其簡單使用和筆者在使用時所遇到的問題做一些總結。

本文參考了該博文:http://blog.csdn.net/zgjxwl/article/details/9627685

 

一、WebView中Java與javascript互動

1.這是要和js互動的注入介面類:

public final class JavascriptInteerface{        @JavascriptInterface        public void test(String teststr) {            Toast.makeText(getApplicationContext(), teststr, Toast.LENGTH_LONG).show();        }        @JavascriptInterface        public void test1() {
       // 調用js代碼 webView.loadUrl(
"javascript:testJavaCall(‘這是java調js的方法‘)"); }}

2.這是互動的代碼,其中data裡的window.testObject.test(‘這是js掉java的Test方法‘)是調用java的代碼

webView.getSettings().setJavaScriptEnabled(true);webView.addJavascriptInterface(new JavascriptInteerface(), "testObject");// 測試的HTML代碼String data ="<HTML><HEAD><script type=\"text/javascript\">function testJavaCall(str){alert(str);};</script></HEAD><BODY><H1>TEST1</H1></BODY><BR /><INPUT type=\"button\" value=\"js調用java\" onclick=\"window.testObject.test(‘這是js掉java的Test方法‘)\" /><INPUT type=\"button\" value=\"java調js\" onclick=\"window.testObject.test1()\" /></HTML>";// 如果是網頁,直接用loadUrl(url)方法webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);

 

二、使用時遇見android版本相容的問題

WebView存在android系統版本升級導致的相容性問題。本文主要討論的是java和js的互動問題。4.2版本之前和4.2版本(包含)之後接入js是有所區別的。

在之前,筆者使用的注入互動介面類如下:

public final class JavascriptInteerface{        public void test() {            Toast.makeText(getApplicationContext(), "這是java代碼的Test方法", Toast.LENGTH_LONG).show();        }}

調用為:

webView.getSettings().setJavaScriptEnabled(true);webView.addJavascriptInterface(new JavascriptInteerface(), "testObject");

按照上面的方法,在My Phone(android系統版本為4.4.2)上運行沒有反應,查看log時顯示如下錯誤:

E/Web Console﹕ Uncaught TypeError: Object [object Object] has no method ‘test‘ at about:blank:1

原因:因為這個介面允許JavaScript 控制宿主應用程式,這是個很強大的特性,但同時,在4.2的版本前存在重大安全隱患,因為JavaScript 可以使用反射訪問注入webview的java對象的public fields,在一個包含不信任內容的WebView中使用這個方法,會允許攻擊者去篡改宿主應用程式,使用宿主應用程式的許可權執行java代碼。因此4.2以後,任何為JS暴露的介面,都需要加@JavascriptInterface注釋,這樣,這個Java對象的fields 將不允許被JS訪問。

官網對於該問題大概描述如下:

 

public void addJavascriptInterface (Object object, String name)Added in API level 1

Injects the supplied Java object into this WebView. The object is injected into the JavaScript context of the main frame, using the supplied name. This allows the Java object‘s methods to be accessed from JavaScript. For applications targeted to API level JELLY_BEAN_MR1 and above, only public methods that are annotated with JavascriptInterface can be accessed from JavaScript. For applications targeted to API level JELLY_BEAN or below, all public methods (including the inherited ones) can be accessed, see the important security note below for implications.

Note that injected objects will not appear in JavaScript until the page is next (re)loaded. For example:

 class JsObject {
    @JavascriptInterface
    public String toString() { return "injectedObject"; }
 }
 webView.addJavascriptInterface(new JsObject(), "injectedObject");
 webView.loadData("", "text/html", null);
 webView.loadUrl("javascript:alert(injectedObject.toString())");

IMPORTANT:

  • This method can be used to allow JavaScript to control the host application. This is a powerful feature, but also presents a security risk for apps targeting JELLY_BEAN or earlier. Apps that target a version later than JELLY_BEAN are still vulnerable if the app runs on a device running Android earlier than 4.2. The most secure way to use this method is to target JELLY_BEAN_MR1 and to ensure the method is called only when running on Android 4.2 or later. With these older versions, JavaScript could use reflection to access an injected object‘s public fields. Use of this method in a WebView containing untrusted content could allow an attacker to manipulate the host application in unintended ways, executing Java code with the permissions of the host application. Use extreme care when using this method in a WebView which could contain untrusted content.
  • JavaScript interacts with Java object on a private, background thread of this WebView. Care is therefore required to maintain thread safety.
  • The Java object‘s fields are not accessible.
  • For applications targeted to API level LOLLIPOP and above, methods of injected Java objects are enumerable from JavaScript.

 

所以,要解決上述問題:只需要在每個Javascript要調用的Java介面中得每個方法前加上這句@JavascriptInterface。例如我之前的代碼改為

public final class JavascriptInteerface{        @JavascriptInterface        public void test() {            Toast.makeText(getApplicationContext(), "這是java代碼的Test方法", Toast.LENGTH_LONG).show();        }}

 

至此,該問題就得到解決。除了該問題外,在做IOS和Android同時跟同一個HTML5中得JS互動時,也會遇到一個問題,主要是向注入js對象不一樣導致,這種解決方案最好是在IOS向HTML動態注入js代碼;也可以在JS中判斷用戶端使用的裝置,在此就不多做說明。

 

android 中java和javascript互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.