Home

 / Blog / 

WebRTC in WebView - Build Live Mobile Apps with JavaScript

WebRTC in WebView - Build Live Mobile Apps with JavaScript

August 8, 202210 min read

Share

WebRTC Webview | Cover Image

By now, developers are well aware that WebRTC is one of the most optimal protocols to capture and stream audio and video over the internet. It is also used for exchanging arbitrary data between browsers without an intermediary. Essentially, WebRTC enables browsers and apps to share data and perform teleconferencing peer-to-peer, without requiring the user to install plug-ins or any third-party software.

If you’re developing an app that includes audio-video communication, then this piece will discuss a quick, useful hack to help with the process. Using WebRTC as a WebView in your app.

WebView lets you get a browser-like interface right within your mobile application. The WebView allows users to display web content directly within an application. This is especially useful when developers need advanced configuration options and more control over the UI in order to embed web pages in a specially-designed app environment. It also saves time when shipping an app already made for the web to a mobile device.

This article will discuss how to enable WebRTC as a WebView on Android, iOS & Flutter.

Enabling WebView WebRTC

By the end of the tutorial, you’ll know how to add WebRTC apps to different platforms. However, to test out WebRTC, we’ll first have to create relevant deployments so that we can obtain the necessary URLs.

Originally we would have used https://test.webrtc.org or https://apprtc-m.appspot.com to test our integration. However, these publicly available services have been turned down as of 2021-12-1. More information is available here.

In place of the above links, we will use 100ms to create the necessary apps in a few easy steps.

Let’s start by setting up a 100ms project.

  • Go to https://dashboard.100ms.live/ and create an account.

    Setting up the project

  • Create a new app by selecting the Video Conferencing template.

    Selecting the template

  • Click on Deploy Now and configure deployment. Give your app a subdomain and click on Continue.

    Deploying the app

  • Finish creating the app and click on the Invite button.

    Finish setting up the app

  • Copy the URL and save it. We’ll need to use it as WebView in our Android, iOS, and Flutter projects.

    Saving the project

Android WebView & WebRTC

We’ll start by creating a new Android project using Android Studio.

  • Open Android Studio and click on New Project. Select Empty Activity and give the project a name.

Setting up the project in android studio

  • We’ll call it WebviewWebRTC. Click on Finish to create the project.

Fnishing up the project in android studio

  • Inside the MainActivity.kt of the project, add import android.webkit.WebView to the imports. Next, modify the AppCompatActivity as follows:
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val WebView: WebView = findViewById(R.id.webview)
        WebView.settings.javaScriptEnabled = true
        WebView.settings.domStorageEnabled = true
        WebView.setWebChromeClient(object : WebChromeClient() {
            override fun onPermissionRequest(request: PermissionRequest) {
                request.grant(request.resources)
            }
        })
        WebView.loadUrl("https://<your-template-subdomain>.app.100ms.live/preview/<room-code>")
    }
}
  • Here, use the URL created earlier inside loadUrl to launch it.
  • Next, add the following permissions to the AndroidManifest.xml:
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
  • Add the WebView tag in activity_main.xml as shown below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

</androidx.constraintlayout.widget.ConstraintLayout>

The application is now ready for launch.

Click on Run app. Wait for the application to build and launch on the emulator or mobile device you are using.

It should look something as seen below:

Finished Webrtc Webview Android App

iOS WebView & WebRTC

Now, we try setting up the WebView on iOS to test out WebRTC.

  • Start by creating a new iOS project. Under the iOS tab, select App and click on Next. We’ll name this project WebviewWebRTC.

New iOS Project

  • Inside the project, modify the ContentView file. Start by adding the import WebKit
  • Here, add the code as follows:
import SwiftUI
import WebKit

struct ContentView: View {
    @State private var showWebView = false
    
    var body: some View{
        WebView(url: URL(string: "https://<your-template-subdomain>.app.100ms.live/preview/<room-code>")!)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
 
struct WebView: UIViewRepresentable {
    var url: URL
    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }
    func updateUIView(_ webView: WKWebView, context: Context) {
        let request = URLRequest(url: url)
        webView.load(request)
    }
}
  • To access the Camera and Microphone, modify permissions in info.plist
  • Now run the app. Here, we are running the application on an iPhone 12 iOS simulator.
  • It will ask for permission to access the Camera and Microphone. Allow said permissions.

Allowing Permissions

The project should now run. It should operate as seen below:

Finished Webrtc Webview iOS App

Flutter WebView & WebRTC

Lastly, we create a Flutter Project to set up WebRTC in WebView.

  • Run the flutter create webview command to create a new Flutter project. To enable WebView, add the Flutter InAppWebView package by running the command below:
flutter pub add webview_flutter
  • To add Camera and Microphone permissions, run the following command:
flutter pub add permission_handler
  • Modify the main.dart code inside the lib folder as follows:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:webview_flutter/webview_flutter.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Permission.camera.request();
  await Permission.microphone.request();

  runApp(WebviewScreen());
}

class WebviewScreen extends StatefulWidget {
  const WebviewScreen({Key? key}) : super(key: key);

  @override
  State<WebviewScreen> createState() => _WebviewScreenState();
}

class _WebviewScreenState extends State<WebviewScreen> {
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: WebView(
        javascriptMode: JavascriptMode.unrestricted,
        initialUrl: 'https://<your-template-subdomain>.app.100ms.live/preview/<room-code>',
      ),
    );
  }
}
  • Inside AndroidManifest.xml add the following permissions within the <manifest> tag:
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.VIDEO_CAPTURE" />
    <uses-permission android:name="android.permission.AUDIO_CAPTURE" />

Note: To run the application using a Bluetooth device, we might need to set up Bluetooth permissions.

  • Set the compileSdkVersion to 30 in the android/app/build.gradle file:
android {
  compileSdkVersion 30
  ...
}
  • Set the minSdkVersion to 21:
android {
  defaultConfig {
		minSdkVersion 21
		...
	}
  ...
}
  • Run the app. It will ask for permission to access the Camera and Microphone. Allow said permissions.

The app should now run, as seen below:

Finished Webrtc Webview Flutter App

That’s it. We have just successfully set up WebView WebRTC in Android, iOS, and Flutter.

Conclusion

WebView in WebRTC is useful when trying to replicate a website experience within a mobile app. It can come in handy when you have your web app ready and want to view content as seen on a mobile browser inside your application. This makes apps quick and easy to ship and makes developers’ lives easier by a long shot.

Video

Share

Related articles

See all articles