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;
}
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.
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 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.
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 .
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With