5 things about Android WebView you probably didn’t know

Tram Ho

WebView is an indispensable part of applications, it allows to display web pages on the user interface screen. Here are 5 things that when you first approach WebView, you may not know.

1. Intercepting URLs

By implementing the shouldOverrideUrlLoading method during the shouldOverrideUrlLoading initialization WebViewClient, we can intercept the URL during the site's navigation.

This way, we can control whether that URL should be loaded or open a certain activity / service using the Intent .

2. Basic Web Authentication

Many websites will ask users to enter their credentials. When we first setup the WebView , we might miss this and lead to a 401 authentication error when it loads the page.

By implementing the onReceivedHttpAuthRequest method, we can easily implement basic authentication in the WebView :

3. Setting Listeners for WebView Buttons and EditText

When we want to get data from WebView forms, or perform an action when a button inside the WebView is clicked, we can take advantage of Android-JavaScript interoperability.

If we know the view / widget ID in HTML, then executing Android actions based on WebView interactions is pretty straightforward.

Just use the evaluateJavaScript method and pass the JS code as a string. Ideally, it should be done in the onPageLoadFinishing method

The above code is just for getting data from WebView forms when the button is clicked and passing them to the Android.onWebBtnClick method. In order for it to work, we need to create a JavaScript interface class and set it up on the WebView

We set up on WebView as follows:

4. Trigger JavaScript Alert Prompts from Android

By default, prompts from JavaScript do not display natively in Android. So we need to override the onJsAlert , onJsPrompt and onJsConfirm in the WebChromeClient interface to display the alert () of JavaScript and other methods.

By implementing the method below you can show the Android alert:

5. Display Android File Chooser from WebView

We need to implement the onShowFileChooser method in WebChromeClient , in which we have to set the native file selector. Using the ValueCallBack interface of WebKit helps to convert data from Android file picker to JavaScript code. In the onActivityResult method, when we get the data, just pass it to the uploadFile instance in the following way:

And now the selected data has been transferred from Android to JavaScript.




Share the news now

Source : Viblo