A Comprehensive Guide to WebView in Kotlin: Building Embedded Web Browsers

Reza Ramesh
4 min readSep 1, 2023

--

The internet has become an integral part of our daily lives, and as developers, we often need to integrate web content into our mobile applications. One powerful tool at our disposal for achieving this is the WebView widget. In this article, we’ll explore WebView in Kotlin, understand its capabilities, and build a practical example to demonstrate its usage.

What is WebView?

WebView is a widget that allows you to display web content within your Android application. It essentially embeds a web browser inside your app, enabling you to show web pages, handle user interactions with web content, and even communicate between the web content and your app’s code.

WebView is particularly useful for various scenarios, including:

  1. Displaying static web content within your app.
  2. Loading and interacting with dynamic web pages.
  3. Implementing OAuth2 or other web-based authentication flows.
  4. Embedding web-based forms or surveys.
  5. Rendering web-based charts and graphs.
  6. Integrating web-based APIs or services.

Let’s dive into the world of WebView with Kotlin by building a simple example.

Setting Up Your Project

Before we get started, make sure you have Android Studio installed on your machine. Create a new Android project or open an existing one to follow along.

Adding WebView to Your Layout

In your app’s layout XML file, add a WebView element. You can do this by opening the desired layout file (usually located in the res/layout directory) and adding the following code:

<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

This code defines a WebView with the id “webView” that takes up the entire available space within its parent layout.

Loading a Web Page

Now, let’s load a web page into our WebView. In your Kotlin activity file, retrieve the WebView instance and load a web page. Here’s an example:

import android.os.Bundle
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity

class WebViewActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_webview)

// Find the WebView by its id
val webView: WebView = findViewById(R.id.webView)

// Load a web page
val url = "https://www.example.com"
webView.loadUrl(url)
}
}

In this code, we first find the WebView by its id, “webView,” and then use the loadUrl method to load a web page from the specified URL. Replace "https://www.example.com" with the URL you want to display.

Enabling JavaScript

WebView also allows you to enable JavaScript, which is often required for interactive web content. To enable JavaScript, add the following line of code after loading the URL:

webView.settings.javaScriptEnabled = true

This line enables JavaScript support within the WebView, making your web pages more interactive.

Handling WebView Events

WebView provides various callback methods to handle events such as page loading, error handling, and progress tracking. Here’s an example of how to handle the page loading progress and display a progress bar:

webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
// Show a progress bar or loading indicator
progressBar.visibility = View.VISIBLE
}

override fun onPageFinished(view: WebView?, url: String?) {
// Hide the progress bar
progressBar.visibility = View.GONE
}

override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
// Handle errors, e.g., display an error message
Toast.makeText(this@WebViewActivity, "Error: $description", Toast.LENGTH_SHORT).show()
}
}

In this code, we set a WebViewClient to our WebView, which allows us to override methods like onPageStarted, onPageFinished, and onReceivedError to respond to various events during page loading.

Communicating Between JavaScript and Kotlin

WebView also supports communication between JavaScript running in the WebView and your Kotlin code. You can use the addJavascriptInterface method to expose Kotlin objects to JavaScript, allowing you to call Kotlin functions from your web page's JavaScript code.

Here’s a basic example:

class MyJavaScriptInterface(private val context: Context) {

@JavascriptInterface
fun showToast(message: String) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}

val jsInterface = MyJavaScriptInterface(this)
webView.addJavascriptInterface(jsInterface, "Android")

In this code, we define a MyJavaScriptInterface class with a showToast method that can be called from JavaScript. We then create an instance of this class and add it as a JavaScript interface, making it accessible from JavaScript code using the "Android" name.

In your web page’s JavaScript code, you can call the showToast function like this:

Android.showToast("Hello from JavaScript!")

This will display a toast message in your Kotlin activity.

Summary

WebView is a powerful tool for integrating web content into your Android applications, and it opens up a world of possibilities for creating dynamic and interactive user experiences. In this article, we’ve explored the basics of WebView in Kotlin, including how to add it to your layout, load web pages, enable JavaScript, handle events, and communicate between JavaScript and Kotlin.

As you continue to work with WebView, you’ll discover more advanced features and techniques to enhance your app’s web integration capabilities. Happy coding!

--

--

Reza Ramesh

I am an Android developer and UI/UX designer with 4 years of experience in creating engaging and user-friendly mobile applications