1. Home
  2. >
  3. Blog
  4. >
  5. WebRTC in WebView - Build Live Mobile with JavaScript

WebRTC in WebView - Build Live Mobile with JavaScript

August 8, 2022

Blog - 5.png

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 a 100ms project.

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

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

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

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

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

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.

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

  • 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://aadi-video.app.100ms.live/preview/stj-lci-aah")
    }
}
  • 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:

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.

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

struct ContentView: View {
    @State private var showWebView = false
    
    var body: some View{
        WebView(url: URL(string: "https://aadi-video.app.100ms.live/preview/stj-lci-aah")!)
    }
}

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.

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

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://aadi-video.app.100ms.live/preview/stj-lci-aah',
      ),
    );
  }
}
  • 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:

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.


by Aditya Thakur
August 8, 2022
Share article
Share to twitterShare to facebook

Like what you’re reading?

Get Audio/video engineering tips straight into your inbox