IWebView

interface

Namespace: Vuplex.WebView

IWebView is the primary interface for loading and interacting with web content. It contains methods and properties for common browser-related functionality, like LoadUrl(), GoBack(), Reload(), and ExecuteJavaScript().

To create an IWebView, instantiate a WebViewPrefab or CanvasWebViewPrefab. After the prefab is initialized, you can access its IWebView via the WebViewPrefab.WebView property. If your use case requires a high degree of customization, you can instead create an IWebView outside of a prefab (to connect to your own custom GameObject) by using Web.CreateWebView().

For additional functionality, you can cast an IWebView to an interface for a specific feature, like IWithDownloads or IWithPopups. For a list of additional feature interfaces and information about how to use them, see this page.

Summary

Public properties

IsDisposed

bool IsDisposed { get; }

Gets a value indicating whether the instance has been disposed via Dispose().

IsInitialized

bool IsInitialized { get; }

Gets a value indicating whether the instance has been initialized via Init().

PageLoadScripts

List<string> PageLoadScripts { get; }

Gets a list of JavaScript scripts that are automatically executed in every new page that is loaded.

This list is empty by default, but the application can add scripts. When used in conjunction with 3D WebView's message passing API, it's possible to modify the browser's behavior in significant ways, similar to creating browser extensions.

Example

// Add a script that automatically hides all scrollbars.
await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.PageLoadScripts.Add(@"
    var styleElement = document.createElement('style');
    styleElement.innerText = 'body::-webkit-scrollbar { display: none; }';
    document.head.appendChild(styleElement);
");

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

PluginType

WebPluginType PluginType { get; }

Gets the instance's plugin type.

Example

await webViewPrefab.WaitUntilInitialized();
Debug.Log("Plugin type: " + webViewPrefab.WebView.PluginType);

Size

Vector2Int Size { get; }

Gets the webview's size in pixels.

Example

await webViewPrefab.WaitUntilInitialized();
Debug.Log("Size: " + webViewPrefab.WebView.Size);
See also:

Texture

Texture2D? Texture { get; }

Gets the texture for the webview's web content, or null if running in Native 2D Mode. In order to render the texture, the application must use a Material created with CreateMaterial(). Note that the Material returned by CreateMaterial() already has its mainTexture set to this Texture property.

This texture is an "external texture" created with Texture2D.CreateExternalTexture(). An undocumented characteristic of external textures in Unity is that not all Texture2D methods work for them. For example, Texture2D.GetRawTextureData() and ImageConversion.EncodeToPNG() fail for external textures. To compensate, the IWebView interface includes ts own GetRawTextureData() and CaptureScreenshot() methods to replace them.

Another quirk of this texture is that Unity always reports its size as 1300px × 1300px in the editor. In reality, 3D WebView resizes the texture in native code to match the dimensions of the webview, but Unity doesn't provide an API to notify the engine that an external texture's size has changed. So, Unity always reports its size as the initial size that was passed to Texture2D.CreateExternalTexture(), which in 3D WebView's case is 1300px × 1300px.

Example

await webViewPrefab.WaitUntilInitialized();
var material = webViewPrefab.WebView.CreateMaterial();
// Note: the material returned by CreateMaterial() already
// has its mainTexture set to IWebView.Texture, so setting
// it explicitly like this is really only needed if you are
// switching a material from one webview's texture to another.
material.mainTexture = webViewPrefab.WebView.Texture;

Title

string Title { get; }

Gets the current web page title.

Example

// Get the page's title after it finishes loading.
await webViewPrefab.WaitUntilInitialized();
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
Debug.Log("Page title: " + webViewPrefab.WebView.Title);

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: TitleChanged

Url

string Url { get; }

Gets the current URL.

Example

// Get the page's URL after it finishes loading.
await webViewPrefab.WaitUntilInitialized();
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
Debug.Log("Page URL: " + webViewPrefab.WebView.Url);

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: UrlChanged

Public methods

CanGoBack

Task<bool> CanGoBack()

Checks whether the webview can go back with a call to GoBack().

Example

var canGoBack = await webViewPrefab.CanGoBack();

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: GoBack()

CanGoForward

Task<bool> CanGoForward()

Checks whether the webview can go forward with a call to GoForward().

Example

var canGoForward = await webViewPrefab.CanGoForward();

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: GoForward()

CaptureScreenshot

Task<bytes[]> CaptureScreenshot()

Returns a PNG image of the content visible in the webview.

Example

// Get a screenshot and write it to a file.
var screenshotBytes = await webViewPrefab.WebView.CaptureScreenshot();
var filePath = Path.Combine(Application.persistentDataPath, "screenshot.png");
File.WriteAllBytes(filePath, screenshotBytes);

Important notes

  • On iOS, screenshots do not include video content, which appears black.

  • 2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

Click

void Click(int xInPixels, int yInPixels, bool preventStealingFocus = false)

Clicks at the given coordinates in pixels in the web page, dispatching both a mouse down and a mouse up event.

Example

// Click at (250px, 100px).
webViewPrefab.WebView.Click(250, 100);

// Click at (50px, 150px) and prevent stealing focus from another webview.
webViewPrefab.WebView.Click(50, 150, true);

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

Click

void Click(Vector2 normalizedPoint, bool preventStealingFocus = false)

Like Click(int, int, bool?), except it takes a normalized point instead of pixel coordinates.

Example

// Click in the exact center of the page.
webViewPrefab.WebView.Click(new Vector2(0.5f, 0.5f));

// Click in the upper right quadrant of the page
// and prevent stealing focus from another webview.
webViewPrefab.WebView.Click(new Vector2(0.75f, 0.25f), true);

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

Copy

void Copy()

Copies the selected text to the clipboard.

Example

webViewPrefab.WebView.Copy();

Important note

2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

CreateMaterial

Material CreateMaterial()

Creates a Material that can be used to display the webview, or null if running in Native 2D Mode. The returned material already has the webview's Texture set as its mainTexture.

Note that WebViewPrefab and CanvasWebViewPrefab take care of material creation for you, so you only need to call this method directly if you need to create an IWebView instance outside of a prefab with Web.CreateWebView().

Example

GetComponent<Renderer>().material = webView.CreateMaterial();

Cut

void Cut()

Copies the selected text to the clipboard and removes it.

Example

webViewPrefab.WebView.Cut();

Important note

2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

Dispose

void Dispose()

Destroys the webview, releasing all of its resources.

Important note

If you're using a WebViewPrefab or CanvasWebViewPrefab, please call Destroy() on the prefab instead of calling IWebView.Dispose(). Calling IWebView.Dispose() while the prefab is still using the webview can cause issues.

ExecuteJavaScript

Task<string> ExecuteJavaScript(string javaScript)

Executes the given JavaScript in the context of the page and returns the result.

In order to run JavaScript, a web page must first be loaded. You can use WaitForNextPageLoadToFinish() or the LoadProgressChanged event to run JavaScript after a page loads.

Example

await webViewPrefab.WaitUntilInitialized();
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();

// Example 1: Get the text of the first <h1> element on the page.
var headerText = await webViewPrefab.WebView.ExecuteJavaScript("document.getElementsByTagName('h1')[0].innerText");
Debug.Log("H1 text: " + headerText);

// Example 2: Set the web page title to text input by the user.
webViewPrefab.WebView.ExecuteJavaScript(@"
    // Enclose in a block to prevent titleText from being a global variable.
    {
        let titleText = window.prompt('What do you want to set the web page title to?');
        document.title = titleText;
    }
");

// Example 3: Get the URL of the image at the point (500px, 350px).
Vector2Int pointInPixels = new Vector2Int(500, 350);
var imageUrl = await webViewPrefab.WebView.ExecuteJavaScript($@"
    (function() {{
        const element = document.elementFromPoint({pointInPixels.x}, {pointInPixels.y});
        if (element instanceof HTMLImageElement) {{
            return element.currentSrc;
        }}
        return '';
    }})()
");
Debug.Log("Image URL: " + imageUrl);

Important notes

  • For Android, iOS, and UWP, JavaScript variables not enclosed in a block become global variables. Global variables can be assigned to again in subsequent calls to ExecuteJavaScript(), but they cannot be declared again (i.e. using let or var) because doing so will result in a JavaScript error like the following:

    Uncaught SyntaxError: Identifier '{variable_name}' has already been declared

    If your JavaScript declares variables, it is recommended to enclose the JavaScript in a block like shown in example #2 above. This behavior is only exhibited by the 3D WebView packages for Android, iOS, and UWP. For the other 3D WebView packages (Windows, macOS, Android Gecko, and WebGL), JavaScript variables are not declared in the global scope.

  • For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

ExecuteJavaScript

void ExecuteJavaScript(string javaScript, Action<string> callback)

Like the other version of ExecuteJavaScript(), except it uses a callback instead of a Task to return the result. If you don't need the result from executing the JavaScript, you can improve the method's efficiency by passing null as the callback argument.

GetRawTextureData

Task<byte[]> GetRawTextureData()

A replacement for Texture2D.GetRawTextureData() for IWebView.Texture.

Unity's Texture2D.GetRawTextureData() method currently does not work for textures created with Texture2D.CreateExternalTexture(). So, this method serves as a replacement by providing the equivalent functionality. You can load the bytes returned by this method into another texture using Texture2D.LoadRawTextureData().

Example

var webView = webViewPrefab.WebView;
var textureData = await webView.GetRawTextureData();
var texture = new Texture2D(
    webView.Size.x,
    webView.Size.y,
    TextureFormat.RGBA32,
    false,
    false
);
texture.LoadRawTextureData(textureData);
texture.Apply();

Important notes

  • On iOS, the texture data excludes video content, which appears black.

  • 2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

GoBack

void GoBack()

Navigates back to the previous page in the webview's history.

Example

webViewPrefab.WebView.GoBack();

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: CanGoBack()

GoForward

void GoForward()

Navigates forward to the next page in the webview's history.

Example

webViewPrefab.WebView.GoForward();

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: GoForward()

HandleKeyboardInput

void HandleKeyboardInput(string key)

(Deprecated) Renamed to SendKey() in 3D WebView v4.0.

Init

Task Init(int width, int height)

Asynchronously initializes the webview with the given the dimensions in pixels.

Note that you don't need to call this method if you're using one of the prefabs, like WebViewPrefab. You only need to call Init() if you create an IWebView directly with Web.CreateWebView(). Also, this method's signature was updated in 3D WebView v4.

LoadHtml

void LoadHtml(string html)

Loads the webpage contained in the given HTML string. Note that HTML loaded via this method cannot load subresources (e.g. images, CSS, JavaScript) from the local file system (i.e. via file:// URLs). If you need to load subresources from the local file system, please use one of the approaches described in this article instead.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.LoadHtml(@"
  <!DOCTYPE html>
  <html>
    <head>
      <title>Test Page</title>
      <style>
        h1 {
          font-family: Helvetica, Arial, Sans-Serif;
        }
      </style>
    </head>
    <body>
      <h1>LoadHtml Example</h1>
      <script>
        console.log('This page was loaded!');
      </script>
    </body>
  </html>"
);

Important note

For 2D WebView for WebGL, please see this article that describes how this API is impacted by browser limitations.

See also: LoadUrl()

LoadUrl

void LoadUrl(string url)

Loads the given URL. Supported URL schemes:

  • http://, https:// - loads a remote page over HTTP
  • streaming-assets:// - loads a local page from StreamingAssets (equivalent to "file://" + Application.streamingAssetsPath + path)
  • file:// - some platforms support loading arbitrary file URLs

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.LoadUrl("https://vuplex.com");

LoadUrl

void LoadUrl(string url, Dictionary<string, string> additionalHttpHeaders)

Like LoadUrl(string url), but also sends the given additional HTTP request headers when loading the URL. The headers are sent for the initial page load request but are not sent for requests for subsequent resources, like linked JavaScript or CSS files.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.LoadUrl("https://vuplex.com", new Dictionary<string, string> {
    ["Authorization"] = "Basic YWxhZGRpbjpvcGVuc2VzYW1l",
    ["Cookie"] = "foo=bar"
});

Important notes

NormalizedToPoint

Vector2Int NormalizedToPoint(Vector2 normalizedPoint)

Returns a point in pixels for the given normalized point.

Example

webViewPrefab.Clicked += (sender, eventArgs) => {
    var pointInPixels = webViewPrefab.WebView.NormalizedToPoint(eventArgs.Point);
    Debug.Log("Point in pixels: " + pointInPixels);
};

Paste

void Paste()

Pastes text from the clipboard.

Example

webViewPrefab.WebView.Paste();

Important note

2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

See also:

PointToNormalized

Vector2 PointToNormalized(int xInPixels, int yInPixels)

Returns a normalized point for the given x and y coordinates in pixels. This can be used to create normalized points for APIs that accept them, like MovePointer().

Example

var webView = webViewPrefab.WebView;
// Scroll to the right by 50 pixels at (100px, 1300px).
webView.Scroll(
    webView.PointToNormalized(50, 0),
    webView.PointToNormalized(100, 1300)
);

PostMessage

void PostMessage(string data)

Posts a message that JavaScript within the webview can listen for using window.vuplex.addEventListener('message', function(message) {}). The provided data string is passed as the data property of the message object.

For more details, please see this support article.

Example

await webViewPrefab.WebView.WaitUntilInitialized();
// Add some JavaScript to the page to receive the message.
webViewPrefab.WebView.PageLoadScripts(@"
    window.vuplex.addEventListener('message', function(event) {
        console.log('Message received from C#: ' + event.data);
    });
");
// When the page finishes loading, send a message from C# to JavaScript.
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
webViewPrefab.WebView.PostMessage("Hello from C#");

Reload

void Reload()

Reloads the current page.

Example

webViewPrefab.WebView.Reload();

Resize

void Resize(int width, int height)

Resizes the webview to the given dimensions in pixels.

Important notes

See also:

Scroll

void Scroll(int scrollDeltaXInPixels, int scrollDeltaYInPixels)

Scrolls the top-level document by the given delta in pixels. This method works by calling window.scrollBy(), which works for simple web pages but not for all pages. An alternative is to instead use Scroll(Vector2, Vector2) to scroll at a specific location in the page.

Example

// Scroll down by 50 pixels.
webViewPrefab.WebView.Scroll(0, 50);

// Scroll to the left by 20 pixels.
webViewPrefab.WebView.Scroll(-20, 0);

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

Scroll

void Scroll(Vector2 scrollDelta)

Like Scroll(int, int), but accepts a normalized scroll delta instead of values in pixels.

Example

// Scroll down one quarter of the page.
webViewPrefab.WebView.Scroll(new Vector2(0, 0.25f));

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

Scroll

void Scroll(Vector2 scrollDelta, Vector2 point)

Scrolls by the given normalized scroll delta at the given normalized pointer position.

Example

var webView = webViewPrefab.WebView;
// Scroll down by a quarter of the page in the center of the page
webView.Scroll(new Vector2(0, 0.25f), new Vector2(0.5f, 0.5f));

// Scroll to the right by 50 pixels at (100px, 1300px).
webView.Scroll(
    webView.PointToNormalized(50, 0),
    webView.PointToNormalized(100, 1300)
);

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

SelectAll

void SelectAll()

Selects all text, depending on the page's focused element.

Example

webViewPrefab.WebView.SelectAll();

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also:

SendKey

void SendKey(string key)

Dispatches the given keyboard key to the webview.

A key can either be a single character representing a unicode character (e.g. "A", "b", "?") or a JavaScript key value (e.g. "ArrowUp", "Enter", "Backspace", "Delete"). If you need to trigger a modifier key (e.g. control, shift) or trigger keydown and keyup events separately, use the IWithKeyDownAndUp interface instead.

Example

// Type "Hi!" and then submit the Enter key.
webViewPrefab.WebView.SendKey("H");
webViewPrefab.WebView.SendKey("i");
webViewPrefab.WebView.SendKey("!");
webViewPrefab.WebView.SendKey("Enter");

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

SetDefaultBackgroundEnabled

void SetDefaultBackgroundEnabled(bool enabled)

By default, if a web page doesn't specify a background, 3D WebView sets the page's background to white because that's what web browsers typically do. However, an application can use this method to disable the default white background so that pages that don't set a background will instead have a transparent background. Note that this method must be called before a web page is loaded in order for it to take effect for that page.

Example

await webViewPrefab.WaitUntilInitialized();
// Disable the default white background so the page can be transparent.
webViewPrefab.WebView.SetDefaultBackgroundEnabled(false);

Important note

Nearly all of the 3D WebView packages support transparent webviews, but there are two exceptions:

SetFocused

void SetFocused(bool focused)

Makes the webview take or relinquish focus.

Example

webViewPrefab.WebView.SetFocused(true);

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

SetRenderingEnabled

void SetRenderingEnabled(bool enabled)

Enables or disables the webview's ability to render to its texture. By default, a webview renders web content to its texture, but you can use this method to disable or re-enable rendering.

Example

webViewPrefab.WebView.SetRenderingEnabled(false);

Important note

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

StopLoad

void StopLoad()

Stops the current page load if one is in progress.

Example

webViewPrefab.WebView.StopLoad();

WaitForNextPageLoadToFinish

Task WaitForNextPageLoadToFinish()

Returns a task that completes when the next page load finishes loading, or throws a PageLoadFailedException if the page load fails.

Example

await webViewPrefab.WaitUntilInitialized();
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
Debug.Log("The web page finished loading.");

ZoomIn

void ZoomIn()

Zooms into the currently loaded web content. Note that the zoom level gets reset when a new page is loaded.

Example

// Zoom in after the page finishes loading.
await webViewPrefab.WaitUntilInitialized();
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
webViewPrefab.WebView.ZoomIn();

Important notes

  • On Windows and macOS, adjusting the zoom also affects other webviews viewing the same site, similar to how tabs behave in a desktop browser.

  • 2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

ZoomOut

void ZoomOut()

Zooms back out after a previous call to ZoomIn(). Note that the zoom level gets reset when a new page is loaded.

Example

// Zoom out after the page finishes loading.
await webViewPrefab.WaitUntilInitialized();
await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
webViewPrefab.WebView.ZoomOut();

Important notes

  • On Windows and macOS, adjusting the zoom also affects other webviews viewing the same site, similar to how tabs behave in a desktop browser.

  • 2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

Public events

CloseRequested

EventHandler CloseRequested

Indicates that JavaScript in the page has called window.close(). Calling window.close() doesn't automatically close a webview, but the application can listen to this CloseRequested event to detect when window.close() is called and then choose whether to destroy the webview in response to it.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.CloseRequested += (sender, eventArgs) => {
        Debug.Log("Destroying the WebViewPrefab because window.close() was called.");
        webViewPrefab.Destroy();
};

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

ConsoleMessageLogged

EventHandler<ConsoleMessageEventArgs> ConsoleMessageLogged

Indicates that a message was logged to the JavaScript console.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.ConsoleMessageLogged += (sender, eventArgs) => {
    Debug.Log($"Console message logged: [{eventArgs.Level}] {eventArgs.Message}");
};

Important notes

  • The 3D WebView packages for Android with Gecko, iOS, and UWP have the following limitations:

    • Only messages explicitly passed to a console method like console.log() are included, and other messages like uncaught errors or network errors aren't automatically included.
    • Messages from iframes aren't included.
    • Messages logged early when the page starts loading may be missed.
  • For Android Gecko, an alternative that avoids these limitations is to call AndroidGeckoWebView.SetConsoleOutputEnabled().

  • For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

FocusedInputFieldChanged

EventHandler<FocusedInputFieldChangedEventArgs> FocusedInputFieldChanged

Indicates when an input field has been focused or unfocused. This can be used, for example, to determine when to show or hide an on-screen keyboard. This event is also raised when a focused input field is clicked subsequent times.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.FocusedInputFieldChanged += (sender, eventArgs) => {
    Debug.Log("Focused input field changed. Text input is focused: " + (eventArgs.Type == FocusedInputFieldType.Text));
};

Important notes

  • When an <iframe> element is focused, the event the event specifies the type FocusedInputFieldType.IFrame. This is because the event's implementation is unable detect the type of element that is focused inside an <iframe>.

  • For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

LoadFailed

EventHandler<LoadFailedEventArgs> LoadFailed

Indicates that the page failed to load due to an error. This can happen, for example, if DNS is unable to resolve the hostname.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.LoadFailed += (sender, eventArgs) => {
    Debug.Log($"Load failed. Error code: {eventArgs.NativeErrorCode}, URL: {eventArgs.Url}");
};

Important note

2D WebView for WebGL doesn't support this API due to browser limitations. For more information, please see this article.

LoadProgressChanged

EventHandler<ProgressChangedEventArgs> LoadProgressChanged

Indicates changes in the loading status of a web page. This event can be used, for example, to detect when a page finishes loading or to implement a load progress bar. This event indicates the following types of load events:

  • Started: a new page started loading.
  • Updated: the load progress percentage was updated.
  • Finished: a page finished loading.
  • Failed: a page failed to load.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.LoadProgressChanged += (sender, eventArgs) => {
    Debug.Log($"Load progress changed: {eventArgs.Type}, {eventArgs.Progress}");
    if (eventArgs.Type == ProgressChangeType.Finished) {
        Debug.Log("The page finished loading");
    }
};

Important note

For 2D WebView for WebGL, LoadProgressChanged only indicates the ProgressChangeType.Started and Finished events, and it's unable to indicate the Failed or Updated events.

MessageEmitted

EventHandler<EventArgs<string>> MessageEmitted

Indicates that JavaScript running in the page used the window.vuplex.postMessage JavaScript API to emit a message to the Unity application. For more details, please see this support article.

Example

await webViewPrefab.WaitUntilInitialized();
// Add JavaScript to the page that sends a message.
webViewPrefab.WebView.PageLoadScripts.Add(@"
    window.vuplex.postMessage('Hello from JavaScript!');
");
webViewPrefab.WebView.MessageEmitted += (sender, eventArgs) => {
    Debug.Log("Message received from JavaScript: " + eventArgs.Value);
};

Terminated

EventHandler<TerminatedEventArgs> Terminated

Indicates that the browser engine reported that its process for the webview terminated unexpectedly, either because the web process crashed or because it was killed by the operating system. The webview cannot be used after it has been terminated, so if this event occurs, the webview must be destroyed, and then the application can optionally create a new webview to replace it. 3D WebView is only aware that the browser engine reported that its process terminated, and 3D WebView doesn't have any additional insights into what caused the termination. For more details, you can visit the documentation for the native platform APIs that 3D WebView uses to detect termination:

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.Terminated += (sender, eventArgs) => {
    Debug.Log("The web content process was terminated. Reason: " + eventArgs.Type);
    // Destroy the webview because it can't be used any more.
    webViewPrefab.Destroy();
    // TODO: If the application still needs a webview, it can create a new one with WebViewPrefab.Instantiate().
};

TitleChanged

EventHandler<EventArgs<string>> TitleChanged

Indicates that the page's title changed.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.TitleChanged += (sender, eventArgs) => {
    Debug.Log("Page title changed: " + eventArgs.Value);
};

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: Title

UrlChanged

EventHandler<UrlChangedEventArgs> UrlChanged

Indicates that the URL of the webview changed, either due to user interaction or JavaScript.

Example

await webViewPrefab.WaitUntilInitialized();
webViewPrefab.WebView.UrlChanged += (sender, eventArgs) => {
    Debug.Log("URL changed: " + eventArgs.Url);
};

Important note

For 2D WebView for WebGL, this API is often disabled due to browser limitations. For more information, please see this article.

See also: Url