AndroidWebView

class : IWebView

Namespace: Vuplex.WebView

AndroidWebView is the IWebView implementation used by 3D WebView for Android. It also includes additional APIs for Android-specific functionality.

Summary

Public methods

ClearHistory

void ClearHistory()

Clears the webview's back / forward navigation history.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.ClearHistory();
#endif

GetNativeWebView

AndroidJavaObject GetNativeWebView()

Returns the instance's native android.webkit.WebView.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    var nativeWebView = androidWebView.GetNativeWebView();
    // Call the android.webkit.WebView.findAll() method to search for the letter "a".
    // https://developer.android.com/reference/android/webkit/WebView#findAll(java.lang.String)
    // Most native WebView methods must be called on the Android UI thread.
    AndroidWebView.RunOnAndroidUIThread(() => {
        nativeWebView.Call<int>("findAll", "a");
    });
#endif

Important note

Warning: Adding code that interacts with the native WebView directly may interfere with 3D WebView's functionality and vice versa. So, it's highly recommended to stick to 3D WebView's C# APIs whenever possible and only use GetNativeWebView() if truly necessary. If 3D WebView is missing an API that you need, feel free to contact us.

IsWebViewAvailable

static bool IsWebViewAvailable()

Indicates whether the Android System WebView package is installed on the system and available.

3D WebView internally depends on Android's System WebView package, which is normally installed as part of the operating system. In rare circumstances, the Android System WebView package may be unavailable. For example, this can happen if the user used developer tools to delete the System WebView package or if updates to the System WebView package are currently being installed.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    Debug.Log("WebView is available: " + AndroidWebView.IsWebViewAvailable());
#endif

LoadHtml

void LoadHtml(string html, string baseUrl)

Like IWebView.LoadHtml(), but also allows a virtual base URL to be specified. Setting a base URL allows, for example, for additional resources like CSS and JavaScript files to be referenced via a relative path.

Example

// Load some HTML that references a javascript.js file
// located in Application.persistentDataPath.
await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    var persistentDataPathFileUrl = "file://" + Application.persistentDataPath;
    androidWebView.LoadHtml(
        @"<div>
            <script src='javascript.js'></script>
            <h1>Hello!</h1>
        </div>",
        persistentDataPathFileUrl
    );
#endif

Pause

void Pause()

Pauses processing, media, and rendering for this webview instance until Resume() is called.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.Pause();
#endif

PauseAll

static void PauseAll()

Pauses processing, media, and rendering for all webview instances.

This method is automatically called by the plugin when the application is paused. This method internally calls android.webkit.WebView.pauseTimers(), which globally affects all native webview instances. So, if your project contains other plugins that use the System WebView (for example, ad SDKs), they can be affected by this method. If you find that 3D WebView is interfering with an ad SDK or other plugin in your project that uses the System WebView, please add the scripting symbol VUPLEX_ANDROID_DISABLE_AUTOMATIC_PAUSING to your project to prevent 3D WebView from automatically calling this method.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    AndroidWebView.PauseAll();
#endif

PostUrl

void PostUrl(string url, byte[] data)

Loads the given URL using an HTTP POST request and the given application/x-www-form-urlencoded data.

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.PostUrl("https://postman-echo.com/post", Encoding.Unicode.GetBytes("foo=bar"));
#endif

Resume

void Resume()

Resumes processing and rendering for all webview instances after a previous call to Pause().

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.Resume();
#endif

ResumeAll

static void ResumeAll()

Resumes processing and rendering for all webview instances after a previous call to PauseAll(). This method is automatically called by the plugin when the application resumes after being paused.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    AndroidWebView.ResumeAll();
#endif

RunOnAndroidUIThread

static void RunOnAndroidUIThread(Action function)

Runs the given function on the Android UI thread.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    AndroidWebView.RunOnAndroidUIThread(() => {
        // TODO: Do something on the Android UI thread.
    });
#endif

SetCameraEnabled

static void SetCameraEnabled(bool enabled)

Like Web.SetCameraAndMicrophoneEnabled(), but enables only the camera without enabling the microphone. In addition to calling this method, you must also complete the additional steps described here in order to successfully enable the camera.

Example

void Awake() {
    #if UNITY_ANDROID && !UNITY_EDITOR
        AndroidWebView.SetCameraEnabled(true);
    #endif
}

SetDrmEnabled

static void SetDrmEnabled(bool enabled)

Enables WideVine DRM. DRM is disabled by default because it could potentially be used for tracking. You can verify that DRM is enabled by using the DRM Stream Test on this page.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    AndroidWebView.SetDrmEnabled(true);
#endif

SetForceDark

void SetForceDark(ForceDark forceDark)

Sets the force dark mode for this WebView. Note that this API is only supported on Android API level >= 29 and is ignored in older versions of Android.

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.SetForceDark(ForceDark.On);
#endif

SetFullscreenEnabled

void SetFullscreenEnabled(bool enabled)

By default, web pages can use the JavaScript Fullscreen API to make an HTML element occupy the entire webview in 3D rendering mode or the entire device screen in Native 2D Mode, but this method can be used to disable that capability.

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    await webViewPrefab.WaitUntilInitialized();
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.SetFullscreenEnabled(false);
#endif

SetGeolocationEnabled

static void SetGeolocationEnabled(bool enabled)

By default, web pages cannot access the device's geolocation via JavaScript, even if the user has granted the app permission to access location. Invoking SetGeolocationEnabled(true) allows all web pages to access the geolocation if the user has granted the app location permissions via the standard Android permission dialogs.

The following Android permissions must be included in the app's AndroidManifest.xml and also requested by the application at runtime:

Example

#if UNITY_ANDROID && !UNITY_EDITOR
    AndroidWebView.SetGeolocationEnabled(true);
#endif

Important note

Geolocation doesn't work on Meta Quest devices because they lack GPS support.

SetInitialScale

void SetInitialScale(float scale)

Sets the initial scale for web content, where 1.0 is the default scale.

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.SetInitialScale(1.75f);
#endif

SetMicrophoneEnabled

static void SetMicrophoneEnabled(bool enabled)

Like Web.SetCameraAndMicrophoneEnabled(), but enables only the microphone without enabling the camera. In addition to calling this method, you must also complete the additional steps described here in order to successfully enable the microphone.

Example

void Awake() {
    #if UNITY_ANDROID && !UNITY_EDITOR
        AndroidWebView.SetMicrophoneEnabled(true);
    #endif
}

SetMixedContentMode

void SetMixedContentMode(MixedContentMode mode)

Configures the webview's behavior when a secure origin attempts to load a resource from an insecure origin. The default mode is MixedContentMode.CompatibilityMode.

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.SetMixedContentMode(MixedContentMode.AlwaysAllow);
#endif

SetNativeFileSelectionEnabled

void SetNativeFileSelectionEnabled(bool enabled)

By default, a native file picker is shown for file inputs, but this method can be used to disable it. Note that the screen orientation of the native file picker UI is determined by the "Auto-rotate screen" preference in the device's Settings app.

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.SetNativeFileSelectionEnabled(false);
#endif

SetNativeParentView

static void SetNativeParentView(AndroidJavaObject nativeParentView)

3D WebView for Android is powered by native android.webkit.WebView instances, and it must add those instances to the native Android view hierarchy in order for them to work correctly. By default, 3D WebView adds the native WebView instances as children of the Unity game's ViewGroup, which is obtained using this approach in Java:

ViewGroup parentViewGroup = (ViewGroup)UnityPlayer.currentActivity.getWindow().getDecorView().getRootView();

However, you can call this method at the start of the app to override the ViewGroup to which 3D WebView adds the native WebView instances. For example, you may need to do this if your app embeds Unity as a library, which may cause UnityPlayer.currentActivity to return a different activity than expected.

Example

void Awake() {
    #if UNITY_ANDROID && !UNITY_EDITOR
        AndroidWebView.SetNativeParentView(nativeParentView);
    #endif
}

SetRemoteDebuggingEnabled

static void SetRemoteDebuggingEnabled(bool enabled)

When using 3D rendering mode (i.e. when Native 2D Mode is disabled), remote debugging is enabled by default on Android because some APIs like MovePointer() and SendKey() work better with remote debugging enabled. However, this method can be used to explicitly disable remote debugging. When running in Native 2D Mode, remote debugging is disabled by default.

Example

void Awake() {
    #if UNITY_ANDROID && !UNITY_EDITOR
        AndroidWebView.SetRemoteDebuggingEnabled(false);
    #endif
}

SetScrollbarsEnabled

void SetScrollbarsEnabled(bool enabled)

When Native 2D Mode is enabled, this method sets whether scrollbars are enabled. The default is true. When Native 2D Mode is not enabled, this method has no effect.

Example

await canvasWebViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = canvasWebViewPrefab.WebView as AndroidWebView;
    androidWebView.SetScrollbarsEnabled(false);
#endif

SetSurface

void SetSurface(IntPtr surface)

Sets the Surface to which the webview renders. This can be used, for example, to render to a Meta Quest OVROverlay. After this method is called, the webview no longer renders to its original texture and instead renders to the given surface.

Example

await webViewPrefab.WaitUntilInitialized();
var surface = ovrOverlay.externalSurfaceObject;
webViewPrefab.Resize(ovrOverlay.externalSurfaceWidth, ovrOverlay.externalSurfaceHeight);
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.SetSurface(surface);
#endif

SetTextZoom

void SetTextZoom(int textZoom)

Sets the text zoom of the page in percent. For example, the browser engine automatically adjusts the size of web pages' text by default based on the "Font size" preference in the device's Settings app, but you can use SetTextZoom(100) to force that system font size preference to be ignored.

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.SetTextZoom(100);
#endif

ZoomBy

void ZoomBy(float zoomFactor)

Zooms in or out by the given factor, which is multiplied by the current zoom level to reach the new zoom level. zoomFactor must be in the range from 0.01 to 100.0. Note that the zoom level gets reset when a new page is loaded.

Example

// Zoom by 1.75 after the page finishes loading.
await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.LoadProgressChanged += (sender, eventArgs) => {
    if (eventArgs.Type == ProgressChangeType.Finished) {
        #if UNITY_ANDROID && !UNITY_EDITOR
            var androidWebView = webViewPrefab.WebView as AndroidWebView;
            androidWebView.ZoomBy(1.75f);
        #endif
    }
};

Public events

ScriptAlerted

EventHandler<ScriptDialogEventArgs> ScriptAlerted

Event raised when a script in the page calls window.alert(). If no handler is attached to this event, then window.alert() will return immediately and the script will continue execution. If a handler is attached to this event, then script execution will be paused until the event args' Continue() callback is called.

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.ScriptAlerted += (sender, eventArgs) => {
        Debug.Log("Script alerted: " + eventArgs.Message);
        eventArgs.Continue();
    };
#endif

ScriptConfirmRequested

EventHandler<ScriptDialogEventArgs<bool>> ScriptConfirmRequested

Event raised when a script in the page calls window.confirm(). If no handler is attached to this event, then window.confirm() will return false immediately and the script will continue execution. If a handler is attached to this event, then script execution will be paused until the event args' Continue() callback is called, and window.confirm() will return the value passed to Continue().

Example

await webViewPrefab.WaitUntilInitialized();
#if UNITY_ANDROID && !UNITY_EDITOR
    var androidWebView = webViewPrefab.WebView as AndroidWebView;
    androidWebView.ScriptConfirmRequested += (sender, eventArgs) => {
        Debug.Log("Script confirm requested: " + eventArgs.Message);
        eventArgs.Continue(true);
    };
#endif