[英]JavascriptInterface Method for WebView not called
我有一個很奇怪的問題,我的應用程序是一個電子閱讀器。 為了調用 web 視圖的函數,我使用了一個 JavaScript 類:
public class MyJavaScriptInterface {
Context mContext;
/* Instantiate the interface and set the context */
MyJavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void functionToCall(String input) {
System.out.println("this function was called: "+ input);
}
}
我有一個自定義的 web 視圖,我在其中添加了我的 JavaScript 類。
public class newBTWebView extends WebView implements {
public newBTWebView(Context context) {
super(context);
init(context);
}
public void init(Context context) {
System.out.println("newBTWebview init");
this.context = context;
this.getSettings().setJavaScriptEnabled(true);
setInitialScale(100);
addJavascriptInterface(new MyJavaScriptInterface(this.context), "HTMLOUT");
}
}
在我的主要活動中,我啟動了 Web 視圖並使用 JavaScript 調用該函數:
public class BookReader extends Activity implements WebViewDelegate{
private static Context mContext;
private static newBTWebView testWV;
@Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("onCreate");
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
testWV = (newBTWebView) findViewById(R.id.mywebview1);
testWV.setDelegate(this);
testWV.setWebChromeClient(new WebChromeClient());
testWV.getSettings().setJavaScriptEnabled(true);
testWV.getSettings().setPluginState(PluginState.ON);
testWV.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
System.out.println("shouldOverrideUrlLoading: " + url);
}
@Override
public void onPageFinished(WebView view, String url) {
System.out.println("onPageFinished");
}
}
}
public void callMyFunction
{
System.out.println("callMyFunction");
testWV.loadUrl("javascript:window.HTMLOUT.functionToCall('myinput');”);
}
}
functionToCall 運行良好,最近在我的最新更新中,因為我正在設備上測試應用程序,它仍然可以工作,但是當我在商店提交它時,functionToCall 不再被調用。 我在沒有調用 functionToCall 的設備上測試了 apk 文件。 它僅在我將應用程序直接從 PC 運行到設備時才有效,但在未調用 functionToCall 之前提到的同一設備上使用 apk 文件時才有效。
我已經在三星 S4、三星 Note 10.1 和 nexus note 上進行了測試。 使用安卓 4.4.2、4.0.4 和 5.0.1。
您是否啟用了 proguard 或一些代碼混淆?如果是,您應該添加 keep 屬性
-keep public class com.MyJavaScriptInterface
-keep public class * implements com.MyJavaScriptInterface
-keepclassmembers class * implements com.MyJavaScriptInterface {
<fields>;
<methods>;
}
我不知道你的課程全名。 所以請輸入您的完全限定名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.