Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

triggering JavascriptInterface from a android webview

I followed an instruction to trigger the JavascriptInterface from a webview, but it isnt triggered in my case.

I have an class QuickTextViewer with following:

    public class QuickTextViewer {
        private WebView webView;
    ...
    ...
        public QuickTextViewer(){
           webView = dialog.findViewById(R.id.mywebview);

           webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                 view.loadUrl("javascript:MyApp.resize(document.body.getBoundingClientRect().height)");
                super.onPageFinished(view, url);
            }
        }
@JavascriptInterface
    public void resize(final float height) {
        System.out.print(height);
    }

I also added the following to proguard-rules.pro (actually public only for testing)

-keepclassmembers class fqcn.of.javascript.interface.for.webview {
   public *;
}

In my case onPageFinished is triggered but resize() not ! Any suggestions/help ?

like image 269
mcfly soft Avatar asked May 10 '19 07:05

mcfly soft


People also ask

How to open URL in WebView Android?

Launch an url in an external browser app from your app. startActivity(new Intent(Intent. ACTION_VIEW, Uri.

How to enable JavaScript on WebView?

JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView . You can retrieve WebSettings with getSettings() , then enable JavaScript with setJavaScriptEnabled() . WebView myWebView = (WebView) findViewById(R.

How to use JavaScript in Android WebView?

WebView allows you to bind JavaScript code to Android code through an interface. To do this, we must use the addJavaScriptInterface() method, which is passed the class that provides the interface for JS, and the name that will be used to display the instance in JS (for example, “AndroidFunction“).

How to load WebView in Android?

Modify src/MainActivity. java file to add WebView code. Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.


1 Answers

Found the problem now. Just had to add:

webView.getSettings().setJavaScriptEnabled(true);
like image 196
mcfly soft Avatar answered Oct 10 '22 05:10

mcfly soft