WebViewPrefab

class : MonoBehaviour

Namespace: Vuplex.WebView

WebViewPrefab is a prefab that makes it easy to view and interact with an IWebView in 3D world space. It takes care of creating an IWebView, displaying its texture, and handling pointer interactions from the user, like clicking, dragging, and scrolling. So, all you need to do is specify a URL or HTML to load, and then the user can view and interact with it. For use in a Canvas, see CanvasWebViewPrefab instead.

There are two ways to create a WebViewPrefab:

  1. By dragging the WebViewPrefab.prefab file into your scene via the editor and setting its "Initial URL" property.
  2. Or by creating an instance programmatically with WebViewPrefab.Instantiate(), waiting for it to initialize, and then calling methods on its WebView property, like LoadUrl().

If your use case requires a high degree of customization, you can instead create an IWebView outside of the prefab with Web.CreateWebView().

Summary

Public properties

ClickingEnabled

bool ClickingEnabled

Determines whether clicking is enabled. The default is true.

Collider

Collider Collider { get; }

Gets the prefab's collider

CursorIconsEnabled

bool CursorIconsEnabled

Determines whether the mouse cursor icon is automatically updated based on interaction with the web page. For example, hovering over a link causes the mouse cursor icon to turn into a pointer hand. The default is true. CursorIconsEnabled is currently only supported by 3D WebView for Windows and macOS.

See also: IWithCursorType

DragMode

DragMode DragMode

Determines how the prefab handles drag interactions.

Important notes

DragThreshold

float DragThreshold

Determines the threshold (in web pixels) for triggering a drag. The default is 20.

  • When the prefab's DragMode is set to DragToScroll, this property determines the distance that the pointer must drag before it's no longer considered a click.

  • When the prefab's DragMode is set to DragWithinPage, this property determines the distance that the pointer must drag before it triggers a drag within the page.

HoveringEnabled

bool HoveringEnabled

Determines whether hover interactions are enabled. The default is true.

Important notes

  • This property is ignored when running in Native 2D Mode.

  • For information on the limitations of hovering on iOS and UWP, please see this article.

InitialUrl

string InitialUrl

If you drag a WebViewPrefab.prefab into the scene via the editor, you can set this property in the editor to make it so that the instance automatically loads the given URL after it initializes. To load a new URL at runtime, use IWebView.LoadUrl() instead.

KeyboardEnabled

bool KeyboardEnabled

Determines whether the webview automatically receives keyboard input from the native keyboard and the Keyboard prefab. The default is true.

LogConsoleMessages

bool LogConsoleMessages

Determines whether JavaScript console messages from IWebView.ConsoleMessageLogged are printed to the Unity logs. The default is false.

Material

Material Material { get; set; }

Gets or sets the prefab's material.

NativeOnScreenKeyboardEnabled

bool NativeOnScreenKeyboardEnabled

Determines whether the operating system's native on-screen keyboard is automatically shown when a text input in the webview is focused. The default for WebViewPrefab is false.

Important notes

PixelDensity

float PixelDensity

Sets the webview's pixel density, which is its number of physical pixels per logical pixel. The default value is 1, but increasing it to 2 can make web content appear sharper or less blurry on high DPI displays. PixelDensity is currently only supported by 3D WebView for Windows and macOS.

Example

// Increase the pixel density to 2 for high DPI screens.
webViewPrefab.PixelDensity = 2;

RemoteDebuggingEnabled

bool RemoteDebuggingEnabled

Determines whether the prefab enables remote debugging by calling Web.EnableRemoteDebugging(). The default is false.

Resolution

float Resolution

Gets or sets the prefab's resolution in pixels per Unity unit. You can change the resolution to make web content appear larger or smaller. The default resolution for WebViewPrefab is 1300.

Setting a lower resolution decreases the pixel density, but has the effect of making web content appear larger. Setting a higher resolution increases the pixel density, but has the effect of making content appear smaller. For more information on scaling web content, see this support article.

Example

// Set the resolution to 1800px per Unity unit.
webViewPrefab.Resolution = 1800;

ScrollingEnabled

bool ScrollingEnabled

Determines whether scrolling is enabled. The default is true.

ScrollingSensitivity

float ScrollingSensitivity

Determines the scroll sensitivity. The default sensitivity for WebViewPrefab is 0.005.

Visible

bool Visible { get; set; }

Gets or sets whether the instance is visible and responds to raycasts. The default is true. If you want to hide the webview, setting this property to false is often preferable to disabling the prefab's GameObject, because the latter stops the prefab's scripts from running, which may prevent it from initializating, for example.

WebView

IWebView? WebView { get; }

Returns the prefab's IWebView instance, or null if the prefab hasn't finished initializing yet. To detect when the WebView property is no longer null, please use WaitUntilInitialized().

Example

await webViewPrefab.WaitUntilInitialized();
// Now the WebView property is ready.
webViewPrefab.WebView.LoadUrl("https://vuplex.com");

Public methods

BrowserToScreenPoint

Vector2 BrowserToScreenPoint(int xInPixels, int yInPixels)

Converts the given point from web browser viewport coordinates to the corresponding Unity screen space coordinates of where the point is rendered in the application window. Note that web browser coordinates (the input parameters) treat the top left corner of the browser viewport as the (0, 0) origin. In contrast, Unity's screen space coordinates (the return value) treat the bottom left corner of the application's window as the (0, 0) origin.

Example

var screenPoint = webViewPrefab.BrowserToSreenPoint(200, 300);
Debug.Log($"Point (200px, 300px) within the browser window is rendered at point {screenPoint} on the device screen.");

Destroy

void Destroy()

Destroys the instance and its children. Note that you don't need to call this method if you destroy the instance's parent with Object.Destroy().

Example

// The webview can no longer be used after it's destroyed.
webViewPrefab.Destroy();

Instantiate

static WebViewPrefab Instantiate(float width, float height, WebViewOptions options)

Like Instantiate(float, float), except it also accepts an object of options flags that can be used to alter the generated webview's behavior.

Instantiate

static WebViewPrefab Instantiate(float width, float height)

Creates a new instance with the given dimensions in Unity units. The WebView property is available after initialization completes, which is indicated by WaitUntilInitialized() method. A WebViewPrefab's default resolution is 1300px per Unity unit but can be changed by setting Resolution property.

Example

// Create a 0.5 x 0.5 instance
var webViewPrefab = WebViewPrefab.Instantiate(0.5f, 0.5f);
// Position the prefab how we want it
webViewPrefab.transform.parent = transform;
webViewPrefab.transform.localPosition = new Vector3(0, 0f, 0.5f);
webViewPrefab.transform.LookAt(transform);
// Load a URL once the prefab finishes initializing
await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.LoadUrl("https://vuplex.com");

Instantiate

static WebViewPrefab Instantiate(IWebView webView)

Like Instantiate(float, float), except it initializes the instance with an existing, initialized IWebView instance. This causes the WebViewPrefab to use the existing IWebView instance instead of creating a new one. This can be used, for example, to create multiple WebViewPrefabs that are connected to the same IWebView, or to create a prefab for an IWebView created by IWithPopups.PopupRequested.

Example

await firstWebViewPrefab.WaitUntilInitialized();
var secondWebViewPrefab = WebViewPrefab.Instantiate(firstWebViewPrefab.WebView);
// TODO: Position secondWebViewPrefab to the location where you want to display it.

Resize

void Resize(float width, float height)

Resizes the prefab mesh and webview to the given dimensions in Unity units.

Example

webViewPrefab.Resize(1.2f, 0.5f);
See also:

SetOptionsForInitialization

void SetOptionsForInitialization(WebViewOptions options)

Sets options that can be used to alter the webview that the prefab creates during initialization. This method can only be called prior to when the prefab initializes (i.e. directly after instantiating it or setting it to active).

Example

using System;
using UnityEngine;
using Vuplex.WebView;

class SetOptions : MonoBehaviour {

    // IMPORTANT: With this approach, you must set your WebViewPrefab or CanvasWebViewPrefab to inactive
    //            in the scene hierarchy so that this script can manually activate it. Otherwise, this
    //            script won't be able to call SetOptionsForInitialization() before the prefab initializes.
    //
    // TODO: Set this webViewPrefab field to the inactive WebViewPrefab or CanvasWebViewPrefab in your scene
    //       via the Editor's Inspector tab.
    public BaseWebViewPrefab webViewPrefab;

    void Awake() {

        if (webViewPrefab.gameObject.activeInHierarchy) {
            throw new Exception("The WebViewPrefab object is active in the Editor's scene view. Please set it to inactive so that this script can manually activate it.");
        }
        webViewPrefab.gameObject.SetActive(true);

        webViewPrefab.SetOptionsForInitialization(new WebViewOptions {
            preferredPlugins = new WebPluginType[] { WebPluginType.Android }
        });
    }
}

SetPointerInputDetector

void SetPointerInputDetector(IPointerInputDetector pointerInputDetector)

By default, the prefab detects pointer input events like clicks through Unity's event system, but you can use this method to override the way that input events are detected.

Example

var yourCustomInputDetector = webViewPrefab.Collider.AddComponent<YourCustomInputDetector>();
webViewPrefab.SetPointerInputDetector(yourCustomInputDetector);

SetWebViewForInitialization

void SetWebViewForInitialization(IWebView webView)

By default, the prefab creates a new IWebView during initialization. However, you can call this method before the prefab initializes to pass it an existing, initialized IWebView to use instead. This method can only be called prior to when the prefab initializes (i.e. directly after instantiating it or setting it to active).

WaitUntilInitialized

Task WaitUntilInitialized()

Returns a task that completes when the prefab is initialized, which means that its WebView property is ready for use.

Example

await webViewPrefab.WaitUntilInitialized();
// Now the WebView property is ready.
webViewPrefab.WebView.LoadUrl("https://vuplex.com");

See also: Initialized

WorldToNormalized

Vector2 WorldToNormalized(Vector3 worldPoint)

Converts the given world point to a normalized point in the webview.

Public events

Clicked

EventHandler<ClickedEventArgs> Clicked

Indicates that the prefab was clicked. Note that the prefab automatically calls IWebView.Click() for you.

Example

webViewPrefab.Clicked += (sender, eventArgs) => {
    Debug.Log("WebViewPrefab was clicked at point: " + eventArgs.Point);
};

Initialized

EventHandler Initialized

Indicates that the prefab finished initializing, so its WebView property is ready to use.

PointerEntered

EventHandler PointerEntered

Indicates that the pointer (e.g. mouse cursor) entered the prefab.

PointerExited

EventHandler PointerExited

Indicates that the pointer (e.g. mouse cursor) exited the prefab.

Scrolled

EventHandler<ScrolledEventArgs> Scrolled

Indicates that the prefab was scrolled. Note that the prefab automatically calls IWebView.Scroll() for you.

Example

webViewPrefab.Scrolled += (sender, eventArgs) => {
    Debug.Log($"WebViewPrefab was scrolled. Point: {eventArgs.Point}, scroll delta: {eventArgs.ScrollDelta}");
};