### Example Local HTML File
Source: https://docs.uniwebview.com/guide/loading-local-files.html
This is an example of an HTML file that can be loaded by UniWebView. It includes a link to a CSS file.
```html
Styled heading
```
--------------------------------
### Start Rendering Process for UniWebView
Source: https://docs.uniwebview.com/guide/render-as-texture.html
Call `StartSnapshotForRendering` to enable rendering web content as a texture. This method should be called before accessing texture data. The web view does not need to be visible for this process to start.
```csharp
public class MyBehaviour : MonoBehaviour {
UniWebView webView;
void OpenWebView() {
webView = gameObject.AddComponent();
webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
webView.Load("https://uniwebview.com");
// Start the rendering process.
webView.StartSnapshotForRendering();
}
}
```
--------------------------------
### Start GitHub Authentication Flow
Source: https://docs.uniwebview.com/guide/oauth2-github.html
Call this method in your script's Start() function to initiate the GitHub OAuth2 authentication flow. Ensure the UniWebViewAuthenticationFlowGitHub component is on the same GameObject.
```csharp
void Start() {
var githubFlow = GetComponent();
githubFlow.StartAuthenticationFlow();
}
```
--------------------------------
### Start Authentication Session with Callbacks
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationSession
Starts the authentication session, displaying a secured web page. It includes event handlers for successful authentication and errors. Ensure the callback scheme is correctly configured in your app.
```csharp
var session = UniWebViewAuthenticationSession.Create(
"https://example.com/oauth/authorize?client_id=12345&&scope=profile",
"authExample"
);
session.OnAuthenticationFinished += (_, resultUrl) => {
Debug.Log("Auth flow received callback url: " + resultUrl);
// Continue to exchange the code to the access token.
};
session.OnAuthenticationErrorReceived += (_, errorCode, message) => {
// Error handling.
};
session.Start();
```
--------------------------------
### Start Google OAuth2 Authentication Flow
Source: https://docs.uniwebview.com/guide/oauth2-google.html
Call this method in the Start() function of a script attached to the same GameObject as UniWebViewAuthenticationFlowGoogle to initiate the authentication process.
```csharp
void Start() {
var googleFlow = GetComponent();
googleFlow.StartAuthenticationFlow();
}
```
--------------------------------
### Start Continuous Web View Rendering
Source: https://docs.uniwebview.com/api
Initiates the process of continually rendering the web view's content. Call this before using `GetRenderedData` or `CreateRenderedTexture`. It prepares a render buffer and starts an internal coroutine for fetching snapshot data. You can specify a rendering area, a callback for when rendering starts, and the refresh interval.
```csharp
webView.StartSnapshotForRendering(rect: new Rect(0, 0, 100, 100), onStarted: (texture) => {
// Optional: Perform actions when rendering starts
}, refreshInterval: 1.0f/30f);
```
--------------------------------
### UniWebViewAuthenticationSession.Start
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationSession
Starts the authentication session process, displaying a web page to the user.
```APIDOC
## UniWebViewAuthenticationSession.Start()
### Description
Starts the authentication session process. It will show up a secured web page and navigate users to the `Url`.
### Example
```csharp
var session = UniWebViewAuthenticationSession.Create(
"https://example.com/oauth/authorize?client_id=12345&&scope=profile",
"authExample"
);
session.OnAuthenticationFinished += (_, resultUrl) => {
Debug.Log("Auth flow received callback url: " + resultUrl);
// Continue to exchange the code to the access token.
};
session.OnAuthenticationErrorReceived += (_, errorCode, message) => {
// Error handling.
};
session.Start();
```
```
--------------------------------
### Example CSS File for Styling
Source: https://docs.uniwebview.com/guide/loading-local-files.html
This CSS file styles an H1 element, demonstrating how local resources are loaded.
```css
h1 {
color: red;
}
```
--------------------------------
### StartAuthenticationFlow
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowLine
Starts the authentication flow with the standard OAuth 2.0. This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
```APIDOC
## StartAuthenticationFlow
### Description
Starts the authentication flow with the standard OAuth 2.0.
### Method
void
### Parameters
None
### Response
None
```
--------------------------------
### Start Google Authentication Flow
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowGoogle
Initiate the Google authentication process by calling `StartAuthenticationFlow()`. Ensure all required properties like `clientId`, `redirectUri`, and `scope` are set beforehand.
```csharp
googleFlow.StartAuthenticationFlow();
```
--------------------------------
### Log File Download Start
Source: https://docs.uniwebview.com/api
Use OnFileDownloadStarted to be notified when a file download begins, logging the remote URL and the chosen file name.
```csharp
webView.OnFileDownloadStarted += (view, remoteUrl, fileName) => {
print(string.Format("Download Started. From '{0}', file name '{1}'", remoteUrl, fileName));
};
```
--------------------------------
### Customize Optional Parameters and Start Flow
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowCustomize.html
Configure optional parameters like state and PKCE support, then initiate the authentication flow. This is typically done after attaching the script to a GameObject and setting up its properties in the Unity inspector.
```csharp
public UniWebViewAuthenticationFlowCustomize customize;
customize.optional.enableState = true;
customize.optional.PKCESupport = UniWebViewAuthenticationPKCE.S256;
customize.StartAuthenticationFlow();
```
--------------------------------
### Handle File Download Started Event
Source: https://docs.uniwebview.com/guide/download-files.html
Listen to the `OnFileDownloadStarted` event to be notified when a download begins. This callback provides the remote URL and the determined file name for the download.
```csharp
webView.OnFileDownloadStarted += (view, remoteUrl, fileName) => {
Debug.Log(string.Format("Download Started. From '{0}', file name '{1}'", remoteUrl, fileName));
};
```
--------------------------------
### Migrate Inset Calculation from RunningOnRetinaIOS to Screen Height/Width
Source: https://docs.uniwebview.com/release-note
This example shows the old method of calculating bottom inset using UniWebViewHelper.RunningOnRetinaIOS() and the new, simplified method using UniWebViewHelper.screenHeight. The new method avoids device-specific calculations and UI factors.
```csharp
int uiFactor = UniWebViewHelper.RunningOnRetinaIOS() ? 2 : 1;
int bottomInset = Screen.height / ( 2 * uiFactor );
_webView.insets = new UniWebViewEdgeInsets(0,0,bottomInset,0);
```
```csharp
int bottomInset = (int)(UniWebViewHelper.screenHeight * 0.5f);
_webView.insets = new UniWebViewEdgeInsets(0,0,bottomInset,0);
```
--------------------------------
### Example Google OAuth Client ID Format
Source: https://docs.uniwebview.com/guide/oauth2-google.html
This is an example format for a Google OAuth Client ID generated from the Google Cloud Console. Replace the placeholder parts with your actual generated values.
```text
1234567890-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com
```
--------------------------------
### Load Local HTML from StreamingAssets
Source: https://docs.uniwebview.com/guide/loading-local-files.html
Use UniWebViewHelper.StreamingAssetURLForPath to get the correct URL for local files in the StreamingAssets folder and then load it.
```csharp
var url = UniWebViewHelper.StreamingAssetURLForPath("local_www/index.html");
webView.Load(url);
```
--------------------------------
### StartRefreshTokenFlow
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowLine
Starts the refresh flow with the standard OAuth 2.0. This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
```APIDOC
## StartRefreshTokenFlow
### Description
Starts the refresh flow with the standard OAuth 2.0.
### Method
void
### Parameters
#### Path Parameters
- **refreshToken** (string) - Required - The refresh token to use for the flow.
### Response
None
```
--------------------------------
### Console Log for Received Token
Source: https://docs.uniwebview.com/guide/oauth2-github.html
This is an example of the console log output when a GitHub access token is successfully received. Replace YOUR_ACCESS_TOKEN with the actual token.
```csharp
Token received: ${YOUR_ACCESS_TOKEN}
```
--------------------------------
### Handle UniWebView Channel Messages by Action
Source: https://docs.uniwebview.com/api/UniWebViewChannelMessage.html
Listen for channel messages and handle them based on the 'action' property. This example demonstrates a switch statement to process different actions like 'getUserInfo' and 'saveScore'. Unknown actions are logged as warnings.
```csharp
webView.OnChannelMessageReceived += (view, message) => {
switch (message.action) {
case "getUserInfo":
// Handle user info request
break;
case "saveScore":
// Handle score saving
break;
default:
Debug.LogWarning($"Unknown action: {message.action}");
break;
}
return null;
};
```
--------------------------------
### Evaluate JavaScript and Simulate Clicks
Source: https://docs.uniwebview.com/guide/render-as-texture.html
Programmatically interact with web content by evaluating JavaScript. This example shows how to retrieve all links and simulate a click on the first one.
```csharp
webView.OnPageFinished += (view, statusCode, url) => {
webView.EvaluateJavaScript("Array.from(document.links).map(link => link.href);", result => {
var data = UniWebViewExternal.Json.Deserialize(result.data) as List;
// Use the data: ["https://example.com", "https://example.com/link1", ...]
});
};
// Later, simulate the click on the first link.
webView.EvaluateJavaScript("document.links[0].click();");
```
--------------------------------
### Start Facebook Authentication Flow
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowFacebook
Initiates the Facebook authentication process. This method should be called after configuring the necessary properties, such as the App ID.
```csharp
void StartAuthenticationFlow()
```
--------------------------------
### Handle Page Start Event
Source: https://docs.uniwebview.com/api
Use this event to execute code when a web view begins loading a URL. It's triggered for both explicit loads and link navigations.
```csharp
webView.OnPageStarted += (view, url) => {
print("Loading started for url: " + url);
};
webView.Load("https://example.com");
// => "Loading started for url: https://example.com/"
```
--------------------------------
### Get Resources for Media Capture Permission Request
Source: https://docs.uniwebview.com/api/UniWebViewChannelMethodMediaCapturePermission.html
Inspect the requested resources, commonly "VIDEO" or "AUDIO", for media capture permission.
```csharp
permission.Resources // ["VIDEO"]
```
--------------------------------
### Get and Apply Toolbar Configuration
Source: https://docs.uniwebview.com/api/UniWebViewEmbeddedToolbar.html
Retrieve the current toolbar configuration, modify its properties, and then apply the changes. This is useful for inspecting the current state or as a base for further customization.
```csharp
// Get the current config as a starting point for modifications.
var config = webView.EmbeddedToolbar.CurrentConfig;
config.BackgroundColor = UniWebViewEmbeddedToolbarConfig.ColorValue.FromColor(Color.black);
webView.EmbeddedToolbar.ApplyConfig(config);
```
--------------------------------
### Retrieve Screen Size in Points with UniWebViewHelper
Source: https://docs.uniwebview.com/release-note
Use UniWebViewHelper.screenHeight and UniWebViewHelper.screenWidth to get the screen dimensions in points, which is useful for calculating insets, especially after the deprecation of RunningOnRetinaIOS.
```csharp
int screenHeight = UniWebViewHelper.screenHeight;
int screenWidth = UniWebViewHelper.screenWidth;
```
--------------------------------
### OnPageStarted
Source: https://docs.uniwebview.com/api
Raised when the web view starts loading a URL. This event is invoked for both URL loading with the `Load` method or by a link navigating from a page.
```APIDOC
## OnPageStarted
### Description
Raised when the web view starts loading a url. This event will be invoked for both URL loading with `Load` method or by a link navigating from a page.
### Parameters
#### Path Parameters
- **webView** (UniWebView) - The web view component which raises this event.
- **url** (string) - The url which the web view is about to load.
### Request Example
```csharp
webView.OnPageStarted += (view, url) => {
print("Loading started for url: " + url);
};
webView.Load("https://example.com");
// => "Loading started for url: https://example.com/"
```
```
--------------------------------
### Enable Auto-Play for Media in UniWebView
Source: https://docs.uniwebview.com/api
Set this static method before creating a web view to allow media to start playing automatically via media tag attributes. Existing web views are not affected.
```csharp
UniWebView.SetAllowAutoPlay(true);
// Create a new web view.
var webView = gameObject.AddComponent();
// Now load and open a page which contains auto-started video to try
webView.Load("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_video_autoplay");
webView.Show();
```
--------------------------------
### Start Refresh Token Flow
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowCustomize.html
Begin the OAuth 2.0 token refresh process by providing the current refresh token. This method implements the abstract method from UniWebViewAuthenticationCommonFlow.
```csharp
void StartRefreshTokenFlow(string refreshToken)
```
--------------------------------
### HTML Video Tag Example
Source: https://docs.uniwebview.com/guide/playing-videos.html
This is an example of an HTML video tag with the `autoplay` attribute. Note that auto play is not enabled by default in UniWebView.
```html
```
--------------------------------
### Start Google Refresh Token Flow
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowGoogle
Begin the process of refreshing an access token using a provided refresh token. Call `StartRefreshTokenFlow()` with the valid refresh token.
```csharp
googleFlow.StartRefreshTokenFlow(refreshToken);
```
--------------------------------
### Enable Verbose Logging
Source: https://docs.uniwebview.com/guide/channel-message.html
Enable detailed logging for channel message activity by setting `UniWebViewLogger.Instance.LogLevel` to `UniWebViewLogger.Level.Verbose` in the `Start` function. This helps in debugging message types, responses, and errors.
```csharp
void Start() {
// Enable detailed logging
UniWebViewLogger.Instance.LogLevel = UniWebViewLogger.Level.Verbose;
}
```
--------------------------------
### Get UniWebView Navigation History
Source: https://docs.uniwebview.com/api
Retrieves a snapshot of the web view's navigation history. This list is read-only and does not update automatically. Call this method again to get the latest history.
```csharp
webView.OnPageFinished += (view, statusCode, url) => {
PrintList();
};
```
--------------------------------
### Enable Prefetching with Alternative URL
Source: https://docs.uniwebview.com/api/uniwebviewsafebrowsing.html
Enables Custom Tabs prefetching using `mayLaunchUrl` before showing the tab. An alternative URL can be specified.
```csharp
safeBrowsing.SetPrefetch(true, "https://prefetch-example.com");
```
--------------------------------
### GetPopupWindow
Source: https://docs.uniwebview.com/api
Gets a popup window handle by its identifier.
```APIDOC
## GetPopupWindow
### Description
Gets a popup window handle by its identifier.
### Method
UniWebViewPopup
### Parameters
- **multipleWindowId** (string) - The identifier of the popup window.
### Returns
The UniWebViewPopup handle for the specified identifier.
```
--------------------------------
### UniWebViewShadow Properties
Source: https://docs.uniwebview.com/api/UniWebViewShadow
Properties to get the styling of the UniWebView shadow.
```APIDOC
## UniWebViewShadow
### Properties
- **Radius** (float): Blur radius of the shadow in pixels.
- **Opacity** (float): Shadow opacity, clamped between `0` and `1`.
- **OffsetX** (float): Horizontal offset of the shadow relative to the container.
- **OffsetY** (float): Vertical offset of the shadow relative to the container.
- **Spread** (float): Extra expansion distance applied to the shadow outline.
- **Color** (Color): Color tint of the shadow. The alpha channel multiplies with `Opacity`.
- **IsVisible** (bool): Returns `true` when the shadow will be rendered (opacity greater than zero and radius/spread greater than zero).
### Static Properties
- **None** (UniWebViewShadow): Returns a predefined shadow definition that disables rendering (no blur, zero opacity).
```
--------------------------------
### GetUserAgent
Source: https://docs.uniwebview.com/api
Gets the user agent string currently used in the web view.
```APIDOC
## GetUserAgent
### Description
Gets the user agent string currently used in web view.
### Method
string
### Returns
The current user agent string.
```
--------------------------------
### Enable New Window Support
Source: https://docs.uniwebview.com/guide/support-new-window.html
Call `SetSupportMultipleWindows(true, false)` to enable the behavior where links with `target="_blank"` open in a new tab. This adds a temporary web view layer above the current one.
```csharp
webView.SetSupportMultipleWindows(true, false);
```
--------------------------------
### CopyBackForwardList
Source: https://docs.uniwebview.com/api
Gets a copy of the back-forward list, which is the navigation history for the web view.
```APIDOC
## CopyBackForwardList
### Description
Gets a copy of the back-forward list, which is the navigation history for the web view.
### Method
UniWebViewBackForwardList
### Returns
A copy of the back-forward list.
```
--------------------------------
### Configure and Load Web View Content
Source: https://docs.uniwebview.com/guide/working-with-code.html
Configures the UniWebView's frame to fill the screen, loads a specified URL, and makes the web view visible. Use this after creating the UniWebView component.
```csharp
webView.Frame = new Rect(0, 0, Screen.width, Screen.height); // 1
webView.Load("https://docs.uniwebview.com/game.html"); // 2
webView.Show(); // 3
```
--------------------------------
### UniWebViewBackForwardList Properties
Source: https://docs.uniwebview.com/api/UniWebViewBackForwardList
Access properties of the UniWebViewBackForwardList to get information about the navigation history.
```APIDOC
## Properties
### AllItems
List AllItems { get; }
Gets all items in the back-forward navigation history list.
### CurrentItem
UniWebViewBackForwardItem CurrentItem { get; }
Gets the current page item in the navigation history.
It is the page that is currently displayed in the list. If there is no item in the list, it will return null.
### BackItem
UniWebViewBackForwardItem BackItem { get; }
Gets the previous (back) page item in the navigation history.
Returns null if there is no previous page.
### ForwardItem
UniWebViewBackForwardItem ForwardItem { get; }
Gets the next (forward) page item in the navigation history.
Returns null if there is no next page.
### CurrentIndex
int CurrentIndex { get; }
Gets the index of current page in the navigation history.
The index is zero-based in the list. If there is no item in the list, it will return -1.
### Size
int Size { get; }
Gets the total number of items in the navigation history.
```
--------------------------------
### Create and Show Safe Browsing Instance
Source: https://docs.uniwebview.com/api/uniwebviewsafebrowsing.html
Creates a new UniWebViewSafeBrowsing instance for a given URL and then displays it.
```csharp
UniWebViewSafeBrowsing safeBrowsing = UniWebViewSafeBrowsing.Create("https://example.com");
safeBrowsing.Show();
```
--------------------------------
### UniWebViewAuthenticationFlowFacebook Methods
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowFacebook
Methods available for interacting with the Facebook authentication flow, primarily for starting the process.
```APIDOC
## Methods
### `void StartAuthenticationFlow()`
Starts the authentication flow with the standard OAuth 2.0. This implements the abstract method in `UniWebViewAuthenticationCommonFlow`.
```
--------------------------------
### StartSnapshotForRendering
Source: https://docs.uniwebview.com/api
Initiates the continuous rendering of web view snapshots, optionally with a specified area and refresh rate.
```APIDOC
## StartSnapshotForRendering
### Description
Starts the process of continually rendering the snapshot.
### Method
void
### Parameters
#### Path Parameters
- **rect** (Rect?) - Optional - The rectangular area to capture for rendering.
- **onStarted** (Action) - Optional - A callback action to be executed when rendering starts.
- **refreshInterval** (float) - Optional - The interval in seconds at which to refresh the rendering. Defaults to 0.
```
--------------------------------
### UniWebViewMessage Properties
Source: https://docs.uniwebview.com/api/uniwebviewmessage
Access properties of a UniWebViewMessage to get details about the message received from web content.
```APIDOC
## UniWebViewMessage Properties
### RawMessage
Gets the raw message. It is the original url which initialized this message.
**Example**
```csharp
webView.OnMessageReceived += (view, message) => {
print(message.RawMessage);
};
webView.Load("uniwebview://action?key=value&anotherKey=value");
// => "uniwebview://action?key=value&anotherKey=value"
```
### Scheme
The url scheme of this UniWebViewMessage. "uniwebview" was added to message scheme list by default. You can add your own scheme by using `UniWebView.AddUrlScheme`.
**Example**
```csharp
webView.OnMessageReceived += (view, message) => {
print(message.Scheme);
};
webView.Load("uniwebview://action?key=value&anotherKey=value");
// => "uniwebview"
// Use a customized scheme.
anotherWebView.AddUrlScheme("myscheme");
anotherWebView.OnMessageReceived += (view, message) => {
print(message.Scheme);
};
anotherWebView.Load("myscheme://action");
// => "myscheme"
```
### Path
The path of this UniWebViewMessage.
**NOTICE**
This will be the decoded value for the path of original url.
**Example**
```csharp
webView.OnMessageReceived += (view, message) => {
print(message.Path);
};
webView.Load("uniwebview://action?key=value&anotherKey=value");
// => "action"
// Encoded path
webView.OnMessageReceived += (view, message) => {
print(message.Path);
};
webView.Load("uniwebview://%e8%b7%af%e5%be%84?key=value&anotherKey=value");
// => "路径"
```
### Args
The arguments of this UniWebViewMessage. UniWebView will try to parse the url query into a dictionary.
When received url "uniwebview://yourPath?param1=value1¶m2=value2", the args is a `Dictionary` with: Args["param1"] = value1, Args["param2"] = value2
**NOTICE**
Both the key and value will be url decoded from the original url.
**Example**
```csharp
// Basic key-value args
webView.OnMessageReceived += (view, message) => {
print(message.Args["key"]);
print(message.Args["anotherKey"]);
};
webView.Load("uniwebview://action?key=value&anotherKey=anotherValue");
// => "value"
// => "anotherValue"
// With the same key
webView.OnMessageReceived += (view, message) => {
print(message.Args["key"]);
};
var message = new UniWebViewMessage("uniwebview://sample_message?key=1&key=2");
// => "1,2"
// With encoded key and value
webView.OnMessageReceived += (view, message) => {
print(message.Args["键"]);
};
var message = new UniWebViewMessage("uniwebview://sample_message?%E9%94%AE=%E5%80%BC);
// => "值"
```
```
--------------------------------
### Show Web View with Animations
Source: https://docs.uniwebview.com/api
Displays the web view on screen, with options for fade-in and edge-based transition animations. A completion handler can be provided to execute code after the animation finishes.
```csharp
// Show the web view without animation
webView.Show();
```
```csharp
// Show the web view with a fade animation
webView.Show(true);
```
```csharp
// Show the web view with a modal presenting animation from screen bottom
webView.Show(false, UniWebViewTransitionEdge.Bottom);
```
```csharp
// Print a message after the web view shown with animation
webView.Show(true, UniWebViewTransitionEdge.Top, 0.25f, ()=> {
print("Show transition finished!");
});
```
--------------------------------
### CanGoForward
Source: https://docs.uniwebview.com/api
Gets a boolean value indicating whether there is a next page available in the back-forward navigation history.
```APIDOC
## CanGoForward
### Description
Gets whether there is a forward page in the back-forward list that can be navigated to.
### Property
`bool CanGoForward { get; }`
```
--------------------------------
### CanGoBack
Source: https://docs.uniwebview.com/api
Gets a boolean value indicating whether there is a previous page available in the back-forward navigation history.
```APIDOC
## CanGoBack
### Description
Gets whether there is a back page in the back-forward list that can be navigated to.
### Property
`bool CanGoBack { get; }`
```
--------------------------------
### Show
Source: https://docs.uniwebview.com/api
Sets the web view visible on screen.
```APIDOC
## Show
### Description
Sets the web view visible on screen.
### Method
bool
### Parameters
- **fade** (bool) - Whether to use a fade animation.
- **edge** (UniWebViewTransitionEdge) - The edge for the transition.
- **duration** (float) - The duration of the transition.
- **completionHandler** (Action) - The action to perform upon completion.
```
--------------------------------
### OnFileDownloadStarted
Source: https://docs.uniwebview.com/api
This event is fired when a file download initiated by UniWebView begins. It provides the remote URL of the file and the filename chosen for the download.
```APIDOC
## OnFileDownloadStarted
### Description
Raised when a file download task starts. It provides the remote URL of the file and the filename chosen for the download.
### Parameters
#### Path Parameters
- **webView** (UniWebView) - The web view component which raises this event.
- **remoteUrl** (string) - The remote URL of this download task. This is also the download URL for the task.
- **fileName** (string) - The file name which user chooses to use.
### Request Example
```csharp
webView.OnFileDownloadStarted += (view, remoteUrl, fileName) => {
print(string.Format("Download Started. From '{0}', file name '{1}'", remoteUrl, fileName));
};
```
```
--------------------------------
### Url
Source: https://docs.uniwebview.com/api
Gets the URL of the currently loaded web page. This property provides read-only access to the current URL.
```APIDOC
## Url
### Description
The url of current loaded web page.
### Property
`string Url { get; }`
### Example
```csharp
webView.Load("https://example.com/");
// Some time later or in "OnPageFinished":
print(webView.Url);
// => "https://example.com/"
```
```
--------------------------------
### OnPageCommitted
Source: https://docs.uniwebview.com/api
Raised when the web view receives a response from the server and starts receiving web content. This happens after `OnPageStarted` but before `OnPageFinished`.
```APIDOC
## OnPageCommitted
### Description
Raised when the web view receives response from the server and starts receiving web content. This event will be invoked when the web view has confirmed the response is a web page and has started to receive and process the web content. This happens after `OnPageStarted` but before `OnPageFinished`.
### Parameters
#### Path Parameters
- **webView** (UniWebView) - The web view component which raises this event.
- **url** (string) - The url which the web view has started receiving content for.
### Request Example
```csharp
webView.OnPageCommitted += (view, url) => {
Debug.Log("Web View starts receiving content, URL: " + url);
// Inject JavaScript code at early stage
view.EvaluateJavaScript("console.log('Early stage injection');", null);
};
```
```
--------------------------------
### Enable JavaScript Window Opening
Source: https://docs.uniwebview.com/guide/support-new-window.html
Call `SetAllowJavaScriptOpenWindow(true)` before creating the web view to allow UniWebView to receive opening requests. Then, call `SetSupportMultipleWindows(true, true)` to enable multiple windows and JavaScript-initiated openings.
```csharp
UniWebView.SetAllowJavaScriptOpenWindow(true);
var webView = // Creating the web view component...
webView.SetSupportMultipleWindows(true, true);
// Then, you can use JavaScript like `window.open` to open the web view.
```
--------------------------------
### UniWebViewAuthenticationFlowCustomize Methods
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowCustomize.html
Methods to initiate and manage the authentication and refresh flows.
```APIDOC
## Methods Summary
### void StartAuthenticationFlow()
Starts the authentication flow with the standard OAuth 2.
### void StartRefreshTokenFlow(string refreshToken)
Starts the refresh flow with the standard OAuth 2.
```
--------------------------------
### Log Level Configuration
Source: https://docs.uniwebview.com/api/uniwebviewlogger.html
You can get and set the current logging level. Messages with a severity lower than the current LogLevel will not be logged.
```APIDOC
## UniWebViewLogger
### Properties
UniWebViewLogger.Level LogLevel { get; set; }
Current level of this logger. All messages above current level will be logged out.
The default level is `Critical`, which means the logger only prints errors and exceptions.
UniWebViewLogger.Level Level.Verbose { get; }
Lowest level. When set to `Verbose`, the logger will log out all messages.
UniWebViewLogger.Level Level.Debug { get; }
Debug level. When set to `Debug`, the logger will log out most of messages up to this level.
UniWebViewLogger.Level Level.Info { get; }
Info level. When set to `Info`, the logger will log out up to info messages.
UniWebViewLogger.Level Level.Critical { get; }
Critical level. When set to `Critical`, the logger will only log out errors or exceptions.
UniWebViewLogger.Level Level.Off { get; }
Off level. When set to `Off`, the logger will log out nothing.
```
--------------------------------
### Get Current URL
Source: https://docs.uniwebview.com/api
Retrieves the URL of the currently loaded web page. This is useful for tracking navigation or displaying the current address.
```csharp
webView.Load("https://example.com/");
// Some time later or in "OnPageFinished":
print(webView.Url);
// => "https://example.com/"
```
--------------------------------
### Build UniWebView Embedded Toolbar Config from Scratch
Source: https://docs.uniwebview.com/guide/embedded-toolbar.html
Create a completely custom toolbar configuration by instantiating `UniWebViewEmbeddedToolbarConfig` and setting its properties. This allows full control over visibility, position, colors, and button content.
```csharp
var config = new UniWebViewEmbeddedToolbarConfig();
config.Visible = true;
config.Position = UniWebViewToolbarPosition.Top;
config.BackgroundColor = UniWebViewEmbeddedToolbarConfig.ColorValue.FromColor(Color.black);
config.ButtonTextColor = UniWebViewEmbeddedToolbarConfig.ColorValue.FromColor(Color.cyan);
// Left: only a back button.
config.Left.Add(
UniWebViewEmbeddedToolbarConfig.Item.BuiltIn(
UniWebViewEmbeddedToolbarConfig.BuiltInItemKind.Back, title: "←"
)
);
// Center: title with interactions.
config.Center.Add(
UniWebViewEmbeddedToolbarConfig.Item.BuiltIn(
UniWebViewEmbeddedToolbarConfig.BuiltInItemKind.Title,
title: "Browser",
titleInteraction: new UniWebViewEmbeddedToolbarConfig.TitleInteraction {
OnTap = UniWebViewEmbeddedToolbarConfig.TitleInteraction.TapAction.ScrollToTop,
OnLongPress = UniWebViewEmbeddedToolbarConfig.TitleInteraction.LongPressAction.CopyUrl,
CopyToastText = "Link copied!"
}
)
);
// Right: reload and done.
config.Right.Add(
UniWebViewEmbeddedToolbarConfig.Item.BuiltIn(
UniWebViewEmbeddedToolbarConfig.BuiltInItemKind.Reload
)
);
config.Right.Add(
UniWebViewEmbeddedToolbarConfig.Item.BuiltIn(
UniWebViewEmbeddedToolbarConfig.BuiltInItemKind.Done, title: "✕"
)
);
webView.EmbeddedToolbar.ApplyConfig(config);
```
--------------------------------
### UniWebView Properties
Source: https://docs.uniwebview.com/api
Properties of the UniWebView class that allow you to get or set various aspects of the web view's behavior and appearance.
```APIDOC
## Properties
### IsWebViewSupported
- **Description**: Whether the web view is supported in the current runtime or not.
- **Type**: `bool`
- **Access**: `get`
### Frame
- **Description**: Gets or sets the frame (position and size) of the current web view.
- **Type**: `Rect`
- **Access**: `get`, `set`
### ReferenceRectTransform
- **Description**: A reference RectTransform which the web view should change its position and size to.
- **Type**: `RectTransform`
- **Access**: `get`, `set`
### Url
- **Description**: The URL of the currently loaded web page.
- **Type**: `string`
- **Access**: `get`
### CanGoBack
- **Description**: Gets whether there is a back page in the back-forward list that can be navigated to.
- **Type**: `bool`
- **Access**: `get`
### CanGoForward
- **Description**: Gets whether there is a forward page in the back-forward list that can be navigated to.
- **Type**: `bool`
- **Access**: `get`
### BackgroundColor
- **Description**: Gets or sets the background color of the web view.
- **Type**: `Color`
- **Access**: `get`, `set`
### Alpha
- **Description**: Gets or sets the alpha value of the whole web view.
- **Type**: `float`
- **Access**: `get`, `set`
### EmbeddedToolbar
- **Description**: Represents the embedded toolbar in the current web view.
- **Type**: `UniWebViewEmbeddedToolbar`
- **Access**: `get`
### RestoreViewHierarchyOnResume
- **Description**: Sets whether this web view instance should try to restore its view hierarchy when resumed.
- **Type**: `bool`
- **Access**: `get`, `set`
```
--------------------------------
### Accessing Scheme in UniWebViewMessage
Source: https://docs.uniwebview.com/api/uniwebviewmessage
Get the URL scheme of the UniWebViewMessage. By default, 'uniwebview' is used, but custom schemes can be added using UniWebView.AddUrlScheme.
```csharp
webView.OnMessageReceived += (view, message) => {
print(message.Scheme);
};
webView.Load("uniwebview://action?key=value&anotherKey=value");
// => "uniwebview"
// Use a customized scheme.
anotherWebView.AddUrlScheme("myscheme");
anotherWebView.OnMessageReceived += (view, message) => {
print(message.Scheme);
};
anotherWebView.Load("myscheme://action");
// => "myscheme"
```
--------------------------------
### Show
Source: https://docs.uniwebview.com/api
Makes the web view visible on screen, with optional fade and edge animations. A completion handler can be provided to execute code after the animation finishes.
```APIDOC
## Show
### Description
Sets the web view visible on screen. If you pass `false` and `UniWebViewTransitionEdge.None` to the first two parameters, it means no animation will be applied when showing. So the `duration` parameter will not be taken into account. Otherwise, when either or both `fade` and `edge` set, the showing operation will be animated. Regardless of there is an animation or not, the `completionHandler` will be called if not `null` when the web view showing finishes.
### Parameters
#### Path Parameters
- **fade** (bool) - Optional - Whether show with a fade in animation. Default is `false`.
- **edge** (UniWebViewTransitionEdge) - Optional - The edge from which the web view showing. It simulates a modal effect when showing a web view. Default is `UniWebViewTransitionEdge.None`.
- **duration** (float) - Optional - Duration of the showing animation. Default is `0.4f`.
- **completionHandler** (Action) - Optional - Completion handler which will be called when showing finishes. Default is `null`.
### Return Value
A `bool` value indicates whether the showing operation started.
### Request Example
```csharp
// Show the web view without animation
webView.Show();
// Show the web view with a fade animation
webView.Show(true);
// Show the web view with a modal presenting animation from screen bottom
webView.Show(false, UniWebViewTransitionEdge.Bottom);
// Print a message after the web view shown with animation
webView.Show(true, UniWebViewTransitionEdge.Top, 0.25f, ()=> {
print("Show transition finished!");
});
```
```
--------------------------------
### Handle Loading Errors
Source: https://docs.uniwebview.com/api
Subscribe to the OnLoadingErrorReceived event to handle errors during web view loading. This example logs a message when an error occurs.
```csharp
webView.OnLoadingErrorReceived += (view, code, message, payload) => {
PrintList();
};
```
--------------------------------
### Create UniWebViewSafeBrowsing Instance
Source: https://docs.uniwebview.com/api/uniwebviewsafebrowsing.html
Creates a new UniWebViewSafeBrowsing instance for a given URL. The URL must use the http or https scheme.
```csharp
var safeBrowsing = UniWebViewSafeBrowsing.Create("https://uniwebview.com");
```
--------------------------------
### UniWebViewEmbeddedToolbarConfig Methods
Source: https://docs.uniwebview.com/api/UniWebViewEmbeddedToolbarConfig
Methods for creating, serializing, and managing toolbar configurations.
```APIDOC
## UniWebViewEmbeddedToolbarConfig.FromJson
### Description
Creates a UniWebViewEmbeddedToolbarConfig object from a JSON string.
### Method
`static UniWebViewEmbeddedToolbarConfig FromJson(string json)`
### Parameters
- **json** (string) - Required - The JSON string to parse.
```
```APIDOC
## UniWebViewEmbeddedToolbarConfig.ToJson
### Description
Serializes the UniWebViewEmbeddedToolbarConfig object to a JSON string.
### Method
`string ToJson()`
```
```APIDOC
## UniWebViewEmbeddedToolbarConfig.ToDictionary
### Description
Converts the UniWebViewEmbeddedToolbarConfig object to a dictionary representation that can be serialized to JSON.
### Method
`Dictionary ToDictionary()`
```
```APIDOC
## UniWebViewEmbeddedToolbarConfig.EnumerateItems
### Description
Enumerates all toolbar items across all sections (left, center, right) in order.
### Method
`IEnumerable EnumerateItems()`
```
```APIDOC
## UniWebViewEmbeddedToolbarConfig.FindFirstBuiltInItem
### Description
Finds the first built-in toolbar item matching the given kind across all sections (left, center, right).
### Method
`UniWebViewEmbeddedToolbarConfig.Item FindFirstBuiltInItem(UniWebViewEmbeddedToolbarConfig.BuiltInItemKind kind)`
### Parameters
- **kind** (UniWebViewEmbeddedToolbarConfig.BuiltInItemKind) - Required - The kind of built-in item to find.
```
--------------------------------
### UniWebViewSafeBrowsing.Create
Source: https://docs.uniwebview.com/api/uniwebviewsafebrowsing.html
Creates a new UniWebViewSafeBrowsing instance with a given URL. The URL must use the `http` or `https` scheme.
```APIDOC
## UniWebViewSafeBrowsing.Create(string url)
### Description
Creates a new `UniWebViewSafeBrowsing` instance with a given URL.
### Parameters
#### Path Parameters
- **url** (string) - Required - The URL to navigate to. The URL must use the `http` or `https` scheme.
### Request Example
```csharp
var safeBrowsing = UniWebViewSafeBrowsing.Create("https://uniwebview.com");
```
```
--------------------------------
### Get StreamingAssets URL
Source: https://docs.uniwebview.com/api/uniwebviewhelper
Use this method to create a URL for a file within the StreamingAssets folder. Pass the relative path from the StreamingAssets directory.
```csharp
var url = UniWebViewHelper.StreamingAssetURLForPath("www/localHTML.html");
webView.Load(url);
```
--------------------------------
### Get Host of Media Capture Permission Request
Source: https://docs.uniwebview.com/api/UniWebViewChannelMethodMediaCapturePermission.html
Retrieve the host, typically the domain, of the web page requesting media capture permission.
```csharp
permission.Host // "webrtc.github.io"
```
--------------------------------
### StartSnapshotForRendering
Source: https://docs.uniwebview.com/api
Initiates the continuous rendering of the web view's snapshot. This method prepares a render buffer and starts an internal coroutine to fetch snapshot data periodically. After calling this, `GetRenderedData` and `CreateRenderedTexture` can be called safely from `Update()`. Remember to call `StopSnapshotForRendering` when done to release resources.
```APIDOC
## StartSnapshotForRendering
### Description
Starts the process of continually rendering the web view's snapshot, preparing it for retrieval via `GetRenderedData` or `CreateRenderedTexture`.
### Method
`void StartSnapshotForRendering(Rect? rect = null, Action onStarted = null, float refreshInterval = 0)`
### Parameters
#### Path Parameters
- **rect** (Rect?) - Optional - The area of the view to render. Defaults to the entire view if null.
- **onStarted** (Action) - Optional - A callback executed when rendering starts, receiving the rendered texture.
- **refreshInterval** (float) - Optional - The interval in seconds between snapshot refreshes. Defaults to every frame (0) for maximum responsiveness. A larger value reduces CPU/GPU usage.
```
--------------------------------
### Show/Hide Web View with Fade and Edge Transition
Source: https://docs.uniwebview.com/guide/transition.html
Use the Show and Hide methods with fade and edge parameters for animated transitions. Ensure only one transition is active at a time.
```csharp
webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
webView.Show(true, UniWebViewTransitionEdge.Bottom, 0.35f);
// Later
webView.Hide(true, UniWebViewTransitionEdge.Bottom, 0.35f);
```
--------------------------------
### OnSafeBrowsingNavigationStarted
Source: https://docs.uniwebview.com/api/uniwebviewsafebrowsing.html
Raised when the underlying browser starts loading a page in Safe Browsing mode. This event is not raised on iOS/macOS because Safari does not expose a navigation-start callback.
```APIDOC
## Event: OnSafeBrowsingNavigationStarted
### Description
Raised when the underlying browser starts loading a page in Safe Browsing mode.
NOTICE: This event is not raised on iOS/macOS because Safari does not expose a navigation-start callback.
### Parameters
* **browsing** (UniWebViewSafeBrowsing) - The `UniWebViewSafeBrowsing` object raised this event.
* **metadata** (UniWebViewSafeBrowsingEventMetadata) - Structured metadata describing the native callback.
### Example
```csharp
safeBrowsing.OnSafeBrowsingNavigationStarted += (browsing, metadata) => {
Debug.Log($"Navigation started at {metadata.TimestampUtc}");
};
```
```
--------------------------------
### Customize Toolbar with Config Object
Source: https://docs.uniwebview.com/guide/embedded-toolbar.html
Applies a custom configuration to the embedded toolbar, starting from the default settings. Allows modification of title text and colors.
```csharp
var config = UniWebViewEmbeddedToolbarConfig.Default;
// Set the title.
var titleItem = config.FindFirstBuiltInItem(
UniWebViewEmbeddedToolbarConfig.BuiltInItemKind.Title
);
titleItem.Title = "My App";
// Customize colors.
config.BackgroundColor = UniWebViewEmbeddedToolbarConfig.ColorValue.FromColor(
new Color(0.2f, 0.2f, 0.2f)
);
config.ButtonTextColor = UniWebViewEmbeddedToolbarConfig.ColorValue.FromColor(Color.white);
config.TitleTextColor = UniWebViewEmbeddedToolbarConfig.ColorValue.FromColor(Color.white);
webView.EmbeddedToolbar.ApplyConfig(config);
```
--------------------------------
### Create Smaller Web View for Performance
Source: https://docs.uniwebview.com/guide/render-as-texture.html
Optimize performance by creating a web view with a smaller initial frame size if high resolution is not required for the texture.
```csharp
// webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
webView.Frame = new Rect(0, 0, Screen.width / 4, Screen.height / 4);
```
--------------------------------
### Get Protocol of Media Capture Permission Request
Source: https://docs.uniwebview.com/api/UniWebViewChannelMethodMediaCapturePermission.html
Access the protocol used by the permission request, such as "https" or "http".
```csharp
permission.Protocol // "https"
```
--------------------------------
### SetSupportMultipleWindows
Source: https://docs.uniwebview.com/api
Sets whether the web view should support a pop-up web view triggered by the user in a new tab.
```APIDOC
## SetSupportMultipleWindows
### Description
Sets whether the web view should support a pop up web view triggered by user in a new tab.
### Method
void
### Parameters
- **enabled** (bool) - True to enable support for multiple windows, false otherwise.
- **allowJavaScriptOpening** (bool) - Whether JavaScript is allowed to open new windows.
```
--------------------------------
### Get and Close UniWebView Popup Window
Source: https://docs.uniwebview.com/api
Retrieves a popup window by its ID and evaluates JavaScript to close it. Returns null if the popup is not found or already closed.
```csharp
webView.OnPopupWindowOpened += (view, popup) => {
var samePopup = view.GetPopupWindow(popup.Id);
samePopup?.EvaluateJavaScript("window.close();");
};
```
--------------------------------
### Check Safe Browsing Support and Initialize
Source: https://docs.uniwebview.com/api/uniwebviewsafebrowsing.html
Check if the current runtime supports Safe Browsing. If supported, it indicates that Safe Browsing Mode will be used when `Show` is called. Otherwise, the system's default browser will open the URL. This is crucial for Android 11+ to ensure proper intent handling.
```csharp
if (UniWebViewSafeBrowsing.IsSafeBrowsingSupported) {
// Safe Browsing Mode is available on current device.
}
```
```xml
// ...
```
--------------------------------
### Get Preferred Custom Tabs Provider Package Name
Source: https://docs.uniwebview.com/api/uniwebviewsafebrowsing.html
Retrieves the package name of the Android Custom Tabs provider that UniWebView Safe Browsing will use.
```csharp
string providerPackage = UniWebViewSafeBrowsing.GetSafeBrowsingCustomTabsProviderPackageName();
```
--------------------------------
### Create Blob URL and Trigger Download
Source: https://docs.uniwebview.com/guide/download-files.html
This JavaScript code demonstrates how to create a blob URL from binary data, set it as the `href` for an anchor tag, and programmatically trigger a download. It includes a `setTimeout` to delay revoking the blob URL, ensuring the download can complete.
```javascript
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "sample.png";
a.click();
// Delay the revoke call for a while.
setTimeout(() => {
URL.revokeObjectURL(url);
}, 500);
```
--------------------------------
### Get Server Certificate SHA-256 Fingerprint
Source: https://docs.uniwebview.com/guide/certificate-pinning.html
Use OpenSSL to extract the SHA-256 fingerprint of a server's SSL certificate. This fingerprint is required for certificate pinning.
```bash
echo | openssl s_client -connect self-signed.badssl.com:443 -servername self-signed.badssl.com \
| openssl x509 -fingerprint -sha256 -noout
```
--------------------------------
### Enable Overview Mode Loading
Source: https://docs.uniwebview.com/api
Sets whether pages are loaded in overview mode, zooming out content to fit the screen width. This method is only for Android.
```csharp
void SetLoadWithOverviewMode(bool flag)
```
--------------------------------
### Get Port of Media Capture Permission Request
Source: https://docs.uniwebview.com/api/UniWebViewChannelMethodMediaCapturePermission.html
Obtain the port number associated with the permission request. Returns -1 if the port is not specified in the request URL.
```csharp
permission.Port // -1
```
--------------------------------
### Create UniWebViewAuthenticationSession
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationSession
Creates a new authentication session with a given authentication page URL and a callback scheme. Use this to initiate the OAuth flow.
```csharp
var session = UniWebViewAuthenticationSession.Create(
"https://example.com/oauth/authorize?client_id=12345&&scope=profile",
"authExample"
);
```
--------------------------------
### Configure Optional Settings
Source: https://docs.uniwebview.com/api/UniWebViewAuthenticationFlowGoogle
Customize the behavior of the Google authentication flow using the `optional` property. This includes enabling PKCE, state verification, and setting login hints or prompts.
```csharp
googleFlow.optional.PKCESupport = UniWebViewAuthenticationPKCE.S256;
googleFlow.optional.enableState = true;
googleFlow.optional.loginHint = "user@example.com";
googleFlow.optional.prompt = "consent";
googleFlow.optional.additionalAuthenticationUriQuery = "prompt=consent&ui_locales=en";
```