UniWebView Documentation

repository·master·Indexed 42 days ago

https://github.com/onevcat/uniwebview-docs

Official documentation for UniWebView, a primary interface for managing native web views within Unity. Includes API references for the UniWebView class, covering page loading, JavaScript injection, cookie management, SSL security, and event handling for navigation, popups, and system lifecycle.

Tokens
107.2K
Snippets
316
Records
491
Agent score
52%

What's inside UniWebView

  1. Overview of UniWebView

    master

    UniWebView is a Unity 3D plugin for iOS and Android that enables web view integration within mobile games. It provides high-level C# APIs to manage web content without requiring knowledge of native platform implementations.

    Key capabilities include:

    • Web Content Browsing: Loading HTTP/HTTPS pages or local files, managing size/position, and handling loading events.
    • Interaction: Full JavaScript support, URL messaging, and a Channel messaging system.
    • Advanced Features: OAuth 2.0 support (Authorization Code Flow), video playback (inline or full-screen), image uploading, and rendering web content as a texture.
    • Safe Browsing: A system-level browsing mode for a native experience.
  2. Overview of UniWebView features

    master

    UniWebView is a modern web view component designed for mobile Unity3D games. Key capabilities include:

    • General Web Tasks: Browsing pages, playing videos, interacting with web content, and supporting OAuth 2.0.
    • Communication: High-performance bidirectional communication using an enhanced Channel Messaging System.
    • Extensibility: Well-designed APIs intended for both standard usage and custom extensions.
  3. Understand UniWebView's Privacy and Data Handling

    master

    UniWebView follows the Federal Data Protection Act (BDSG) and the Telemedia Act. The project prioritizes minimal data collection, using personal information only for order processing or responding to issue tickets.

    Key data handling principles:

    • Anonymous Access: Visiting the site or documentation does not require personal information. Only non-identifiable access data (e.g., ISP name, referring page, requested filenames) is collected to improve services.
    • Order Processing: Personal data is only collected when shared during an order or via an issue ticket. Email addresses are stored specifically to identify users for delivering software updates.
    • Data Rights: Users have the right to obtain information about their stored data, and the right to correct, block, or delete it at no charge.
  4. What is Safe Browsing Mode?

    master

    Safe Browsing Mode provides a full-screen, browser-like web experience with a default UI (title and toolbar). It is an out-of-the-box solution designed to show web pages exactly as they appear in a standard browser.

    Key constraints:

    • Only supports web content hosted via HTTP or HTTPS. Loading local file URLs will cause a runtime error.
    • On macOS Editor, it falls back to Application.OpenURL, opening the link in the system's default browser. In this mode, customization and events will not function.
  5. What is UniWebViewShadow?

    master

    The UniWebViewShadow class represents the drop shadow styling applied to the UniWebView container. It maps to native shadow APIs on iOS and Android.

    Values are expressed in Unity pixel units (points on iOS, pixels on Android). UniWebViewShadow is typically used with UniWebView.SetShadow to apply or remove a shadow that follows the same corner radii as the web view.

  6. What is UniWebViewPopup and how to enable it

    master

    A UniWebViewPopup is a lightweight handle used to control temporary overlay web views. These popups are created when a web page triggers target="_blank" or window.open() while multiple window support is enabled.

    To use popups, you must first enable multiple window support on your main UniWebView instance using SetSupportMultipleWindows(true, ...).

  7. How UniWebViewChannelMessage communication patterns work

    master

    UniWebView uses UniWebViewChannelMessage to provide structured, bidirectional communication between web content and Unity via the JavaScript Bridge. There are three distinct communication patterns you must handle correctly in your message handlers:

    1. Send (Fire-and-forget): Used for notifications or one-way data transfer. These messages do not expect a response. Your message handler should return null.
    2. Call (Synchronous): Used when the web content expects an immediate response. The message handler must return a UniWebViewChannelMessageResponse object directly to the JavaScript caller.
    3. Request (Asynchronous): Used for operations that take time (e.g., loading data). The message handler should return null and use the message.Respond() method to send the result back to the JavaScript Promise once the operation completes.

    Use the isFireAndForget, isSyncCall, or isAsyncRequest properties to identify the pattern of an incoming message.

    webView.OnChannelMessageReceived += (view, message) => {
        switch(message.MessageType) {
            case UniWebViewChannelMessageType.Send:
                // Handle fire-and-forget message
                ProcessSendMessage(message);
                return null;
            case UniWebViewChannelMessageType.Call:
                // Handle synchronous call
                return ProcessCallMessage(message);
            case UniWebViewChannelMessageType.Request:
                // Handle asynchronous request
                ProcessRequestMessage(message);
                return null;
        }
        return null;
    };
  8. How the Channel Messaging System works

    master

    The Channel Messaging System is a high-performance bridge for bidirectional communication between web pages and Unity. Unlike the traditional uniwebview:// URL scheme, it supports structured JSON data and offers three distinct communication patterns based on whether the JavaScript side needs a response and how long the operation takes.

    Communication Patterns

    1. Send (Fire-and-Forget): Use window.uniwebview.send(action, data) when notifying Unity of an event where no response is required (e.g., analytics, user interactions).
    2. Call (Synchronous): Use window.uniwebview.call(action, data) when JavaScript needs immediate data from Unity. The execution waits for Unity to return a response. If Unity returns an error, JavaScript throws an exception.
    3. Request (Asynchronous): Use window.uniwebview.request(action, data, [timeout]) for long-running operations (e.g., network calls, file I/O). JavaScript receives a Promise that resolves or rejects based on Unity's response.
    // Send (Fire-and-Forget)
    window.uniwebview.send("actionName", { key: "value" });
    
    // Call (Synchronous)
    const result = window.uniwebview.call("actionName", { key: "value" });
    
    // Request (Asynchronous)
    window.uniwebview.request("actionName", { key: "value" })
      .then(data => console.log(data))
      .catch(err => console.error(err));
  9. Choose between General-Purpose Web View and Safe Browsing Mode

    master

    UniWebView provides two distinct ways to display web content. You can use a Unity prefab for simplified setup or use the full set of APIs via code for both options.

    General-Purpose Web View

    A powerful, highly customizable option. Use this when you need fine-grained control over the web view's integration within your Unity application.

    Safe Browsing Mode

    A simple, secure, full-screen option. It provides a browser-level experience (similar to Mobile Safari or Chrome) with minimal configuration required.

  10. How the legacy StartSnapshotForRendering works

    master

    The StartSnapshotForRendering method is a legacy API used for continually rendering PNG-backed snapshots. It is considered allocation-heavy and is not recommended for new continuous render-as-texture implementations.

    Usage Requirements

    • You must call this method before using GetRenderedData or CreateRenderedTexture. If not called, these methods will return null.
    • Once started, GetRenderedData and CreateRenderedTexture return the latest cached data from the internal buffer, making them safe to call from Update().
    • You must call StopSnapshotForRendering when you no longer need the rendered data to release resources and terminate the internal coroutine.

    Parameters

    • rect (Rect?): The optional area to render. If null, the entire view is rendered.
    • onStarted (Action<Texture>): An optional callback executed when rendering starts. It receives a Texture2D representing the rendered texture.
    • refreshInterval (float): The interval in seconds between refreshes. 0 (default) refreshes every frame. Use larger values (e.g., 1.0f/30) to reduce CPU/GPU usage, which is particularly helpful on Android where snapshot capture runs on the main thread.

    Comparison: Legacy vs. Modern

    FeatureStartSnapshotForRendering (Legacy)StartSnapshotTextureStream (Modern)
    MechanismPNG-backed snapshotsNative texture stream
    PerformanceHigh allocation/CPU costOptimized/Low cost
    CleanupStopSnapshotForRendering()stream.Dispose()
  11. How UniWebViewBackForwardList works

    master

    The UniWebViewBackForwardList class represents the browsing history (back and forward navigation) of a UniWebView instance.

    Key behaviors to note:

    • No direct instantiation: You cannot create this class yourself. You must obtain an instance by calling the CopyBackForwardList method on a UniWebView object.
    • Read-only and Snapshot-based: The list is a fixed snapshot of the history at the moment it is created. It does not automatically update when the web view navigates to new pages.
    • Refreshing history: To get the most up-to-date navigation history, you must call CopyBackForwardList again to generate a new instance.
    // Example of how to obtain the list (conceptual)
    // UniWebViewBackForwardList history = webView.CopyBackForwardList();
  12. Listen to UniWebView loading and lifecycle events

    master

    UniWebView provides an event system to handle page loading and component lifecycle.

    • OnPageFinished: Triggered when a page has finished loading. Use this to execute JavaScript that requires the DOM to be ready.
    • OnShouldClose: Triggered when the web view is about to close (e.g., user clicks a 'Done' button). If you hold a manual reference to the UniWebView instance in your script, you should set that reference to null inside this event to avoid invalid states.

    Note: When OnShouldClose is triggered, the UniWebView component is automatically destroyed by the system.

    // Handle page load completion
    webView.OnPageFinished += (view, statusCode, url) => {
        // Logic to run after page is ready
    };
    
    // Handle cleanup when web view closes
    webView.OnShouldClose += (view) => {
        webView = null;
        return true;
    };