Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add javascript into WebView

I am developing an application where in 1 part I want to add javascript into WebView.. But am not getting how to do it in an appropriate way.. Can anyone pls guide me into this?????

I am doing it like:

      wb=(WebView)findViewById(R.id.webView1);
        wb.getSettings().setJavaScriptEnabled(true);
        wb.getSettings().setPluginState(WebSettings.PluginState.ON);
        wb.getSettings().setPluginsEnabled(true);

        wb.loadUrl("javascript:<script " ></script> ");
        wb.setWebViewClient(new HelloWebViewClient());


 public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
like image 249
Kanika Avatar asked Dec 16 '11 10:12

Kanika


People also ask

How do I enable JavaScript on WebView?

Enable JavaScript 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.

Can WebView run JavaScript?

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“).

Can I use JavaScript to make Android apps?

Can we use JavaScript for Android? Yes, of course! The Android ecosystem supports the concept of hybrid apps, which is a wrapper over the native platform. It mimics the UI, UX, and all kinds of hardware and network interactions, just like how you would use a native Android app.

How do I open an HTML file in WebView?

The WebView method to load our file takes a URI , so we need to access the HTML file using that URI . Since we stored it in the assets folder, we can access it using file:///android_asset/{file_name} . Now let's load that file in our MainActivity .


1 Answers

It was very simple..also without using any javascriptInterface..In my code, Instead writing:

 wb.loadUrl("javascript:<script>   </script>");

use,

  wb.loadDataWithBaseURL(null,"<script>   </script>","text/html","utf-8",null);

and its working now :)

like image 50
Kanika Avatar answered Oct 14 '22 18:10

Kanika