1. 程式人生 > >Js與android webview遭遇過的坑

Js與android webview遭遇過的坑

Uncaught TypeError: Object [object Object] has no method

可能產生該情況有幾種可能

1、安全限制問題

如果只在4.2版本以上的機器出問題,那麼就是系統處於安全限制的問題了。Android文件這樣說的

Caution: If you’ve set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available your web page code (the method must also be public). If you do not provide the annotation, then the method will not accessible by your web page when running on Android 4.2 or higher.

    中文大意為

警告:如果你的程式目標平臺是17或者是更高,你必須要在暴露給網頁可呼叫的方法(這個方法必須是公開的)加上@JavascriptInterface註釋。如果你不這樣做的話,在4.2以以後的平臺上,網頁無法訪問到你的方法。
例:
@JavascriptInterface
public void testMothed(String str) {
}

解決方法

將targetSdkVersion設定成17或更高,引入@JavascriptInterface註釋
自己建立一個註釋介面名字為@JavascriptInterface,然後將其引入。注意這個介面不能混淆。這種方式不推薦,大概在4.4之後有問題。
注,建立@JavascriptInterface程式碼

2、程式碼混淆問題

如果在沒有混淆的版本執行正常,在混淆後的版本的程式碼執行錯誤,並提示Uncaught TypeError: Object [object Object] has no method,那就是你沒有做混淆例外處理。 在混淆檔案加入類似這樣的程式碼

-keepattributes *Annotation*
-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>;
}

本人測試環境是android5.1 moto x 1085