CanvasWebViewPrefab

class : MonoBehaviour

Namespace: Vuplex.WebView

CanvasWebViewPrefab is a prefab that makes it easy to view and interact with an IWebView in a 2D Canvas. 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 outside of a Canvas, see WebViewPrefab instead. For use outside of a Canvas, see WebViewPrefab instead.

There are two ways to create a CanvasWebViewPrefab:

  1. By dragging the CanvasWebViewPrefab.prefab file into your scene via the editor and setting its "Initial URL" property.
  2. Or by creating an instance programmatically with CanvasWebViewPrefab.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.

Important note

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

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.

Important note

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

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 CanvasWebViewPrefab.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.

Important note

This property is unused when running in Native 2D Mode.

Native2DModeEnabled

bool Native2DModeEnabled

Enables or disables Native 2D Mode, which makes it so that 3D WebView positions a native 2D webview in front of the Unity game view instead of displaying web content as a texture in the Unity scene. The default is false. If set to true and the 3D WebView package in use doesn't support Native 2D Mode, then the default rendering mode is used instead. This field can only be set prior to initialization (i.e. prior to when Unity calls Start() for the CanvasWebViewPrefab). Native 2D Mode cannot be enabled or disabled after the webview has been initialized, so changing this field's value after initialization has no effect.

Important notes

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 CanvasWebViewPrefab is true.

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.
canvasWebViewPrefab.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 CanvasWebViewPrefab is 1.

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 2.5px per Unity unit.
webViewPrefab.Resolution = 2.5f;

Important note

When running in Native 2D Mode, the Resolution field isn't used because the device's native resolution is used instead. So, the Resolution field's value is inaccurate and changes to it are ignored.

ScrollingEnabled

bool ScrollingEnabled

Determines whether scrolling is enabled. The default is true.

Important note

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

ScrollingSensitivity

float ScrollingSensitivity

Determines the scroll sensitivity. The default sensitivity for CanvasWebViewPrefab is 15.

Important note

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

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.
canvasWebViewPrefab.Destroy();

Instantiate

static CanvasWebViewPrefab Instantiate(IWebView webView)

Like Instantiate(), except it initializes the instance with an existing, initialized IWebView instance. This causes the CanvasWebViewPrefab to use the existing IWebView instance instead of creating a new one. This can be used, for example, to create multiple CanvasWebViewPrefabs 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 = CanvasWebViewPrefab.Instantiate(firstWebViewPrefab.WebView);
// TODO: Position secondWebViewPrefab to the location where you want to display it.

Instantiate

static CanvasWebViewPrefab Instantiate()

Creates a new instance. The WebView property is available after initialization completes, which is indicated by WaitUntilInitialized().

Example

// Create a CanvasWebViewPrefab
var canvasWebViewPrefab = CanvasWebViewPrefab.Instantiate();
// Position the prefab how we want it
var canvas = GameObject.Find("Canvas");
canvasWebViewPrefab.transform.parent = canvas.transform;
var rectTransform = canvasWebViewPrefab.transform as RectTransform;
rectTransform.anchoredPosition3D = Vector3.zero;
rectTransform.offsetMin = Vector2.zero;
rectTransform.offsetMax = Vector2.zero;
canvasWebViewPrefab.transform.localScale = Vector3.one;
// Load a URL once the prefab finishes initializing
await canvasWebViewPrefab.WaitUntilInitialized();
canvasWebViewPrefab.WebView.LoadUrl("https://vuplex.com");

Instantiate

static CanvasWebViewPrefab Instantiate(WebViewOptions options)

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

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

canvasWebViewPrefab.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 canvasWebViewPrefab.WaitUntilInitialized();
// Now the WebView property is ready.
canvasWebViewPrefab.WebView.LoadUrl("https://vuplex.com");

See also: Initialized

Public events

Clicked

EventHandler<ClickedEventArgs> Clicked

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

Example

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

Important note

This event is not supported when running in Native 2D Mode.

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

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

Important note

This event is not supported when running in Native 2D Mode.