UniWebView
Summary
The main class of UniWebView. It represents a native web view and exposes a few APIs for you to use in
Unity. You could create and use an instance of UniWebView
to show a page from URL, interact with the web content,
as well as receive a message from the web view.
Properties Summary
Get or Set the frame of current web view. | |
A reference rect transform which the web view should change its position and size to. | |
The url of current loaded web page. | |
Gets whether there is a back page in the back-forward list that can be navigated to. | |
Gets whether there is a forward page in the back-forward list that can be navigated to. | |
Gets or sets the background color of web view. | |
Gets or sets the alpha value of the whole web view. |
Events Summary
Raised when the web view starts loading a url. | |
Raised when the web view finished to load a url successfully. | |
Raised when an error encountered during the loading process. | |
Raised when a message from web view is received. | |
Raised when the web view is about to close itself. | |
Raised when a key (like back button or volume up) on the device is pressed. | |
Raised when the screen orientation is changed. | |
Raised when on iOS, when system calls |
Methods Summary
Load a url in current web view. | |
Load an HTML string in current web view. | |
Reloads the current page. | |
Stops loading all resources on the current page. | |
Navigates to the back item in the back-forward list. | |
Navigates to the forward item in the back-forward list. | |
Sets whether the link clicking in the web view should open the page in an external browser. | |
Sets the web view visible on screen. | |
Sets the web view invisible from screen. | |
Animates the web view from current | |
Update and set current frame of web view to match the setting. | |
Adds a JavaScript to current page. | |
Evaluates a JavaScript string on current page. | |
Adds a url scheme to UniWebView message system interpreter. | |
Removes a url scheme from UniWebView message system interpreter. | |
Adds a domain to the SSL checking white list. | |
Removes a domain from the SSL checking white list. | |
Sets a customized header field for web view requests. | |
Sets the user agent used in the web view. | |
Gets the user agent string currently used in web view. | |
Sets the adjustment behavior which indicates how safe area insets are added to the adjusted content inset. | |
Set allow auto-play for current web view. | |
Set allow inline play for current web view. | |
Sets whether JavaScript should be enabled in current web view. | |
Sets whether JavaScript can open windows without user interaction. | |
Sets whether a callout (context) menu should be displayed when user long tapping on certain web view content. | |
Sets whether the web view should support a pop up web view triggered by user in a new tab. | |
Sets the default font size used in the web view. | |
Sets whether the drag interaction should be enabled on iOS. | |
Clean web view cache. | |
Clear all cookies from web views. | |
Sets a cookie for a certain url. | |
Gets the cookie value under a url and key. | |
Clears any saved credentials for HTTP authentication for both Basic and Digest. | |
Sets whether to show a loading indicator while the loading is in progress. | |
Sets the text displayed in the loading indicator, if | |
Sets whether the horizontal scroll bar should show when the web content beyonds web view bounds. | |
Sets whether the vertical scroll bar should show when the web content beyonds web view bounds. | |
Sets whether the web view should show with a bounces effect when scrolling to page edge. | |
Sets whether the web view supports zoom gesture to change content size. | |
Adds a trusted domain to white list and allow permission requests from the domain. | |
Removes a trusted domain from white list. | |
Sets whether the device back button should be enabled to execute "go back" or "closing" operation. | |
Sets whether the web view should enable support for the "viewport" HTML meta tag or should use a wide viewport. | |
Sets whether the web view loads pages in overview mode, that is, zooms out the content to fit on screen by width. | |
Sets whether the web view should behave in immersive mode, that is, hides the status bar and navigation bar with a sticky style. | |
Sets whether to show a toolbar which contains navigation buttons and Done button. | |
Sets the done button text in toolbar. | |
Sets the visibility of navigation buttons, such as "Go Back" and "Go Forward", on toolbar. | |
Sets whether the web view can receive user interaction or not. | |
Enables debugging of web contents. | |
Enables user resizing for web view window. | |
Sets whether file access from file URLs is allowed. | |
Sets whether a prompt alert should be displayed for collection username and password when the web view receives an HTTP authentication challenge (HTTP Basic or HTTP Digest) from server. | |
Gets the HTML content from current page by accessing its | |
Prints current page. | |
Scrolls the web view to a certain point. |
Properties
Get or Set the frame of current web view. The value is based on current Screen.width
and Screen.height
.
The first two values of Rect
is x
and y
position and the followed two width
and height
. The original point is
top left corner:
NOTICE
Frame
will be ignored if ReferenceRectTransform
is set.
Example
// Make the web view full screen:
webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
// Make the web view center in the screen with size 500x500:
var side = 500;
var x = (Screen.width - side) / 2.0f;
var y = (Screen.height - side) / 2.0f;
webView.Frame = new Rect(x, y, side, side);
A reference rect transform which the web view should change its position and size to.
Set it to a Unity UI element (which contains a RectTransform
) under a canvas to determine the web view frame by a certain UI element.
By using this, you could get benefit from Multiple Resolutions UI.
Example
// Some panel
RectTransform panel = ...
// Set the web view position and size to match panel
webView.ReferenceRectTransform = panel;
The url of current loaded web page.
Example
webView.Load("https://example.com/");
// Some time later or in "OnPageFinished":
print(webView.Url);
// => "https://example.com/"
Gets whether there is a back page in the back-forward list that can be navigated to.
Gets whether there is a forward page in the back-forward list that can be navigated to.
Gets or sets the background color of web view. The default value if Color.white
.
This only sets the background color of the content view of the web view. Normally, the background color will be hidden by the web page background. If you want to make the web view background visible, you need to make the web page it transparent by adding some necessary style to it.
This property only changes the web view background.
If you want to make the whole web view transparent, use Alpha
instead.
Example
// Set the web view background (under the web page) to red.
webView.BackgroundColor = Color.red;
Gets or sets the alpha value of the whole web view.
You could make the game scene behind web view visible to make the web view transparent.
The default value is 1.0f
, which means totally opaque. Set it to 0.0f
will make the web view totally transparent.
Example
// Set the web view half transparent.
webView.Alpha = 0.5f;
Events
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.
- UniWebViewwebView
The web view component which raises this event.
- stringurl
The url which the web view begins to load.
Example
webView.OnPageStarted += (view, url) => {
print("Loading started for url: " + url);
};
webView.Load("https://example.com");
// => "Loading started for url: https://example.com/"
Raised when the web view finished to load a url successfully.
This method will be invoked when a valid response received from the URL, regardless the response status.
If a URL loading fails before reaching to the server and getting a response, OnPageErrorReceived
will be
raised instead.
NOTICE
Android did not provide a way to get the HTTP status code until API Level 23 (Android 6).
The statusCode
is not trustable and will be always 200 on Android devices running a system before Android 6.
- UniWebViewwebView
The web view component which raises this event.
- intstatusCode
HTTP status code received from response.
- stringurl
The url which the web view begins to load.
Example
webView.OnPageFinished += (view, statusCode, url) => {
print(statusCode);
print("Web view loading finished for: " + url);
};
webView.Load("https://example.com");
// => "202"
// => "Web view loading finished for: https://example.com"
webView.Load("https://some_domain.com/404");
// => "404"
// => "Web view loading finished for: https://example.com"
Raised when an error encountered during the loading process. Such as host not found or no Internet connection will raise this event.
- UniWebViewwebView
The web view component which raises this event.
- interrorCode
The error code which indicates the error type. It is different from systems and platforms.
- stringurl
The error message which indicates the error.
Example
webView.OnPageErrorReceived += (view, error, message) => {
print("Error.");
};
webView.Load("https://onevcat-not-existing.com/");
// => "Error."
webView.Load("unknown://host?param1=value1¶m2=value2");
// => "Error."
webView.Load("https://self-signed.badssl.com");
// => "Error."
Raised when a message from web view is received.
Generally, the message comes from a navigation to a scheme which is observed by current web view. You could use AddUrlScheme
and
RemoveUrlScheme
to manipulate the scheme list.
"uniwebview://" scheme is default in the list, so a clicking on link starts with "uniwebview://" will raise this event, if it is not removed.
- UniWebViewwebView
The web view component which raises this event.
- UniWebViewMessagemessage
The message object which contains information like message path and arguments.
Example
webView.OnMessageReceived += (view, message) => {
print(message.Scheme);
print(message.Path);
print(message.Args["param1"]);
print(message.Args["param2"]);
}
webView.Load("uniwebview://host?param1=value1¶m2=value2");
// => "uniwebview", "host", "value1", "value2"
anotherWebView.OnMessageReceived += (view, message) => {
print(message.RawMessage);
}
anotherWebView.AddUrlScheme("myscheme");
// Click the link "myscheme://action" in a web page.
// <a href="myscheme://action">Click Me</a>
// => "myscheme://action"
Raised when the web view is about to close itself.
This event is raised when the users close the web view by the Back button on Android, the Done button on iOS, or the Close button on Unity Editor. It gives a chance to make a final decision whether the web view should be closed and destroyed. You should also clean all related resources you created (such as a reference to the web view.)
If this event is not listened and implemented, the web view will be closed and destroyed by default when it needed.
- UniWebViewwebView
The web view component which raises this event.
Whether the web view should be closed and destroyed.
Example
// Clean webView field when
public class MyBehaviour : MonoBehaviour {
var webView;
void Start() {
webView = gameObject.AddComponent<UniWebView>();
webView.OnShouldClose += (view) => {
webView = null;
return true;
};
}
}
// Make the web view there without being closed
webView.OnShouldClose += (view) => {
return false;
};
Raised when a key (like back button or volume up) on the device is pressed.
This event only raised on Android. It is useful when you disabled the back button but still need to get the back button event. On iOS, user's key action is not available and this event will never be raised.
- UniWebViewwebView
The web view component which raises this event.
- intkeyCode
The key code of pressed key. See Android API for keycode to know the possible values.
Example
webView.OnKeyCodeReceived += (view, keyCode) => {
if (keyCode == 4) {
print("Back Button was clicked.");
}
};
Raised when the screen orientation is changed. It is a good time to set the web view frame if you need to support multiple orientations in your game.
- UniWebViewwebView
The web view component which raises this event.
- ScreenOrientationorientation
The screen orientation for current state.
Example
// Keep the web view full screen on both portrait and landscape mode.
webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
webView.OnOrientationChanged += (view, orientation) => {
webView.Frame = new Rect(0, 0, Screen.width, Screen.height);
};
Raised when on iOS, when system calls webViewWebContentProcessDidTerminate
method.
It is usually due to a low memory when loading the web content and leaves you a blank white screen.
You need to free as much as the memory you could and then do a page reload.
- UniWebViewwebView
The web view component which raises this event.
Example
// Clean memory and reload current page
webView.OnWebContentProcessTerminated += (view) => {
// Free memory
// unusedAssets.Clean();
webView.Reload();
};
Methods
Load a url in current web view.
- stringurl
The url to be loaded. This url should start with
http://
orhttps://
scheme. You could even load a non-ascii url text if it is valid. - boolskipEncoding
Whether UniWebView should skip encoding the url or not. If set to
false
, UniWebView will try to encode the url parameter before loading it. Otherwise, your original url string will be used as the url if it is valid. Default isfalse
. - stringreadAccessURL
The URL to allow read access to. This parameter is only used when loading from the filesystem in iOS, and passed to
loadFileURL:allowingReadAccessToURL:
method of WebKit. By default, the parent folder of theurl
parameter will be read accessible.
Example
// Load a URL.
webView.Load("https://example.com");
// Load a URL which is already escaped.
webView.Load("https://example.com?email=support%40uniwebview.com", true);
// Load a local file, with "local_app_folder/root/" as its read access path.
var indexURL = "file://" + "/local_app_folder/root/page/index.html";
var accessURL = "file://" + "/local_app_folder/root/";
webView.Load(indexURL, false, accessURL);
Load an HTML string in current web view.
- stringhtmlString
The HTML string to use as the contents of the webpage.
- stringbaseUrl
The url to use as the page's base url.
- boolskipEncoding
Whether UniWebView should skip encoding the baseUrl or not. If set to
false
, UniWebView will try to encode the baseUrl parameter before using it. Otherwise, your original url string will be used as the baseUrl if it is valid. Default isfalse
.
Example
webView.LoadHTMLString("<p>Hello World</p>", "https://domain.com");
Reloads the current page.
Stops loading all resources on the current page.
Navigates to the back item in the back-forward list.
Example
if (webView.CanGoBack) {
webView.GoBack();
}
Navigates to the forward item in the back-forward list.
Example
if (webView.CanGoForward) {
webView.GoForward();
}
Sets whether the link clicking in the web view should open the page in an external browser.
By default, when the user clicks a link, it will be opened in the same web view. After setting this with true
,
the user will be navigated to an external native browser.
On iOS, the mobile Safari; on Android, the default browser like Chrome; on macOS Editor, the default browser of your system will be used.
- boolflag
The flag indicates whether a link should be opened externally.
Example
// You may want to set it in OnPageFinished event,
// otherwise the original page will be also opened externally
webView.OnPageFinished += (view, statusCode, url) => {
webView.SetOpenLinksInExternalBrowser(true);
};
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.
- boolfade
Whether show with a fade in animation. Default is
false
. - UniWebViewTransitionEdgeedge
The edge from which the web view showing. It simulates a modal effect when showing a web view. Default is
UniWebViewTransitionEdge.None
. - floatduration
Duration of showing animation. Default is
0.4f
. - ActioncompletionHandler
Completion handler which will be called when showing finishes. Default is
null
.
A bool
value indicates whether the showing operation started.
Example
// 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!");
});
Sets the web view invisible from screen.
If you pass false
and UniWebViewTransitionEdge.None
to the first two parameters, it means no animation will be applied when hiding. So the duration
parameter will not be taken into account. Otherwise, when either or both fade
and edge
set, the hiding operation will be animated.
Regardless there is an animation or not, the completionHandler
will be called if not null
when the web view
hiding finishes.
NOTICE
Hiding the web view does not destroy or release it. You could always call Show
on the web view again to make it visible.
To release a web view and its resource, pass the web view component as the parameter of Destroy
.
- boolfade
Whether hide with a fade in animation. Default is
false
. - UniWebViewTransitionEdgeedge
The edge from which the web view hiding. It simulates a modal effect when hiding a web view. Default is
UniWebViewTransitionEdge.None
. - floatduration
Duration of hiding animation. Default is
0.4f
. - ActioncompletionHandler
Completion handler which will be called when hiding finishes. Default is
null
.
A bool
value indicates whether the hiding operation started.
Example
// Hide the web view without animation
webView.Hide();
// Hide the web view with a fade animation
webView.Hide(true);
// Hide the web view with a modal presenting animation from screen bottom
webView.Hide(false, UniWebViewTransitionEdge.Bottom);
// Print a message after the web view hidden with animation
webView.Hide(true, UniWebViewTransitionEdge.Top, 0.25f, ()=> {
print("Hide transition finished!");
});
Animates the web view from current Frame
(position and size) to another Frame
(position and size) within duration
.
- Rectframe
The new
Frame
which the web view should be. - floatduration
Duration of the animation.
- floatdelay
Delay before the animation begins. Default is
0.0f
, which means the animation will start immediately. - ActioncompletionHandler
Completion handler which will be called when animation finishes. Default is
null
.
A bool
value indicates whether the animation started.
Example
// Animate current web view to cover half of the screen.
var halfScreen = new Rect(0, 0, Screen.width, Screen.height / 2);
webView.AnimateTo(halfScreen, 0.4f, 0.1f, () => {
print("Animation finished!");
});
Update and set current frame of web view to match the setting.
This is useful if the referenceRectTransform
is changed and you need to sync the frame change
to the web view. This method follows the frame determining rules.
Example
// In a UIBehavior script:
// Called when associated `rectTransform` is changed.
void OnRectTransformDimensionsChange() {
// This will update web view's frame to match the reference rect transform if set.
webView.UpdateFrame();
}
Adds a JavaScript to current page. Normally, you add a JavaScript function or variable with this method.
The input jsString
will be executed by current web view. If succeeded, the input JavaScript code will "inject"
to the web view and a UniWebViewNativeResultPayload
with resultCode
being "0" will passed to the completionHandler
.
- stringjsString
The JavaScript code to add. It should be a valid JavaScript statement string.
- Action<UniWebViewNativeResultPayload>completionHandler
Called when adding JavaScript operation finishes. Default is
null
. If everything goes fine and thejsString
added to current web view,resultCode
would be "0"
Example
webView.AddJavaScript("function add() { return 1 + 2; }", (payload)=>{
if (result.resultCode.Equal("0")) {
print("JavaScript adding finished without problem.");
}
});
Evaluates a JavaScript string on current page. Normally you execute a certain JavaScript function or get a variable by this method.
The input jsString
will be executed by current web view. Executing result will be sent back to you in the completionHandler
. You could access the data
member of UniWebViewNativeResultPayload
passed in to get the JavaScript function return value.
- stringjsString
The JavaScript string to evaluate.
- Action<UniWebViewNativeResultPayload>completionHandler
Called when evaluating JavaScript operation finishes. Default is
null
. If everything goes find, theresultCode
would be "0" and the return value of invoked JavaScript is contained indata
.
Example
// Pop up an alert from web view.
webView.EvaluateJavaScript("alert('Alert!');", (payload)=>{
print(payload.resultCode); // => "0"
print(payload.data); // => ""
});
// Adding two numbers by a JavaScript function.
webView.AddJavaScript("function add(a, b) { return a + b; }", completionHandler: _ => {
webView.EvaluateJavaScript("add(4, 5);", completionHandler: (payload) => {
print(payload.resultCode); // => "0"
print(payload.data); // => "9"
});
});
// Call a JavaScript function not existing.
webView.EvaluateJavaScript("functionNotExisting()", completionHandler: (payload) => {
print(payload.resultCode);
// a non-zero value which indicates JavaScript error code.
// eg. "4" on iOS.
});
Adds a url scheme to UniWebView message system interpreter. All following url navigation to this scheme will be sent as a message to UniWebView instead.
- stringscheme
The URL scheme to add. It should not contain "://" part. You could even add "http" and/or "https" to prevent all resource loading on the page. "uniwebview" is added by default. Nothing will happen if you try to add a duplicated scheme.
Example
// Add "myscheme" as a UniWebView message scheme.
webView.AddUrlScheme("myscheme");
// A link like "myscheme://action" will be treated as a message and raise the `OnMessageReceived` event from now.
Removes a url scheme from UniWebView message system interpreter.
- stringscheme
The url scheme to remove. Nothing will happen if the scheme is not in the message system.
Example
webView.RemoveUrlScheme("myscheme");
Adds a domain to the SSL checking white list.
If you are trying to access a website with un-trusted or expired certification, the web view will prevent its loading. If you could confirm that this site is trusted, you can add the domain as an SSL exception, so you could visit it.
NOTICE
We strongly suggest you upgrade your site certification to a trusted one. It would be dangerous to add a site as SSL exception and your user might be exposed to the risk of Man-in-the-middle attack. You should know exactly what you will do before adding a domain to the whitelist.
- stringdomain
The domain to add. It should not contain any scheme or path part in url.
Example
// This loading will fail since the certification is a self-signed one and not trusted.
webView.Load("https://self-signed.badssl.com/");
// Add "self-signed.badssl.com" as trusted.
webView.AddSslExceptionDomain("self-signed.badssl.com");
// This page should load now.
webView.Load("https://self-signed.badssl.com/");
Removes a domain from the SSL checking white list.
- stringdomain
The domain to remove. It should not contain any scheme or path part in url.
Example
webView.RemoveSslExceptionDomain("self-signed.badssl.com");
Sets a customized header field for web view requests.
The header field will be used for all subsequence request.
Pass null
as value to unset a header field.
Some reserved headers like user agent are not able to override by setting here,
use the SetUserAgent
method for them instead.
NOTICE
Customized header fields will only be set for GET
requests. The header fields set by this
method will not be added when a form is submitted as POST
requests, due to some limitation of WebKit on iOS
and Android platforms.
- stringkey
The key of customized header field.
- stringvalue
The value of customized header field.
null
if you want to unset the field.
Example
// Set "MyToken" field to "123abc" in a web view. It will be used for all following requests.
webView.SetHeaderField("MyToken", "123abc");
// Unset it
webView.SetHeaderField("MyToken", null);
Sets the user agent used in the web view. If the string is null or empty, the system default value will be used.
- stringagent
The new user agent string to use.
Example
// Set the user agent string sent in request header.
webView.SetUserAgent("My-App/1.0.0 (iOS 10.3, iPhone 7)");
// => In request header:
// User-Agent = "My-App/1.0.0 (iOS 10.3, iPhone 7)"
Gets the user agent string currently used in web view. If a customized user agent is not set, the default user agent in current platform will be returned.
The user agent string in use.
Example
// Gets the default user agent.
webView.GetUserAgent()
// => "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 ..."
// This value varies in different platforms.
// Sets a user agent and then get it.
webView.SetUserAgent("My-App/1.0.0 (iOS 10.3, iPhone 7)");
webView.GetUserAgent()
// => "My-App/1.0.0 (iOS 10.3, iPhone 7)"
Sets the adjustment behavior which indicates how safe area insets
are added to the adjusted content inset. It is a wrapper of contentInsetAdjustmentBehavior
on iOS.
It only works on iOS 11 and above.
NOTICE
You need to call this method as soon as you create a web view,
before you call any other methods related to web view layout (like Show
or SetShowToolbar
).
- UniWebViewContentInsetAdjustmentBehaviorbehavior
The behavior for determining the adjusted content offsets.
Example
var webView = gameObject.AddComponent<UniWebView>();
// Do not adjust the scroll view insets in the web view.
webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never);
Set allow auto-play for current web view. By default, users need to touch the play button to start playing a media resource.
By setting this to true
, you could start the playing automatically through
corresponding media tag attributes.
NOTICE
You need to set it before creating a web view. Existing web views are not affected.
- boolflag
A flag indicates whether auto-playing of media is allowed or not.
Example
UniWebView.SetAllowAutoPlay(true);
// Create a new web view.
var webView = gameObject.AddComponent<UniWebView>();
// 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();
Set allow inline play for current web view. By default, on iOS, the video can only be played in a new full screen view.
By setting this to true
, you could play a video inline the page, instead of opening
a new full-screen window.
This only works for iOS and macOS Editor. On Android, you could play videos inline by default and calling this method does nothing.
Remember you also need to add "playsinline" attribute to your video tag in the HTML page.
NOTICE
You need to set it before creating a web view. Existing web views are not affected.
- boolflag
A flag indicates whether inline playing of media is allowed or not.
Example
UniWebView.SetAllowInlinePlay(true);
// Create a new web view.
var webView = gameObject.AddComponent<UniWebView>();
// Now load and open a page which contains inline video to try:
// <video src="file.mp4" playsinline> or <video src="file.mp4" webkit-playsinline>
webView.Load("https://example.com/inline-video");
webView.Show();
Sets whether JavaScript should be enabled in current web view. Default is enabled.
For a modern page, you may always want JavaScript enabled. However, if you could confirm that you are not using any JavaScript in your page, you could turn it off to get better performance and safety.
NOTICE
You need to set it before creating a web view. Existing web views are not affected.
- boolenabled
Whether JavaScript should be enabled.
Example
// Disable JavaScript in web views created later.
UniWebView.SetJavaScriptEnabled(false);
// JavaScript is disabled in this web view.
var webView = gameObject.AddComponent<UniWebView>();
Sets whether JavaScript can open windows without user interaction.
By setting this to true
, an automatically JavaScript navigation will be allowed in the web view.
- boolflag
Whether JavaScript could open window automatically.
Example
// Allow JavaScript open window automatically.
UniWebView.SetAllowJavaScriptOpenWindow(true);
var webView = gameObject.AddComponent<UniWebView>();
// Now, the following JavaScript code could navigate to
// "example.com" without user interaction in `webView`.
setTimeout(function() {
window.location.href = 'https://example.com';
}, 300);
Sets whether a callout (context) menu should be displayed when user long tapping on certain web view content.
When enabled, when user long presses an image or link in the web page, a context menu would be show up to ask user's action. On iOS, it is a action sheet to ask whether opening the target link or saving the image. On Android it is a pop up dialog to ask whether saving the image to local disk. On iOS, the preview page triggered by force touch on iOS is also considered as a callout menu.
Default is true
, means that the callout menu will be displayed. Call this method with false
to disable it
on the web view.
- boolenabled
Whether a callout menu should be displayed when user long pressing or force touching a certain web page element.
Example
// Disable callout menu in the web view.
webView.SetCalloutEnabled(false);
Sets whether the web view should support a pop up web view triggered by user in a new tab.
In a general web browser (such as Google Chrome or Safari), a URL with target="_blank"
attribute is intended
to be opened in a new tab. However, in the context of web view, there is no way to handle new tabs without
proper configurations. Due to that, by default UniWebView will ignore the target="_blank"
and try to open
the page in the same web view if that kind of link is pressed.
It works for most cases, but if this is a problem to your app logic, you can change this behavior by calling
this method with true
. It enables the "opening in new tab" behavior in a limited way, by adding the new tab
web view above to the current web view, with the same size and position. When the opened new tab is closed,
it will be removed from the view hierarchy automatically.
- boolenabled
Whether to support multiple windows. If
true
, thetarget="_blank"
link will be opened in a new web view. Default isfalse
.
Sets the default font size used in the web view.
On Android, the web view font size can be affected by the system font scale setting. Use this method to set the font size in a more reasonable way, by giving the web view another default font size with the system font scale considered. It can removes or reduces the effect of system font scale when displaying the web content.
This method only works on Android. On iOS, this method does nothing since the web view will respect the font size setting in your CSS styles.
- intsize
The target default font size set to the web view.
Sets whether the drag interaction should be enabled on iOS.
From iOS 11, the iPad web view supports the drag interaction when user long presses an image, link or text.
Setting this to false
would disable the drag feather on the web view.
This method only works on iOS. It does nothing on Android or macOS editor. Default is true
, which means
drag interaction on iPad is enabled.
- boolenabled
Whether the drag interaction should be enabled.
Example
// Disable the drag interaction in the web view.
webView.SetDragInteractionEnabled(false);
Clean web view cache. This removes cached local data of web view.
If you need to clear all cookies, use ClearCookies
instead.
Clear all cookies from web views.
NOTICE
This will clear cookies from all domains in the web view and previous. If you only need to remove cookies from a certain domain, use SetCookie
instead.
Example
UniWebView.ClearCookies();
Sets a cookie for a certain url.
The cookie
string supports all available cookie properties as well as multiple cookies. See
UniWebView respects the server cookie header by default. Generally, you do not need to set the cookie from client manually. However, if you have to pass your server a manually set cookie, use this method.
- stringurl
The url to which cookie will be set.
- stringcookie
The cookie string to set. Need more information on cookie? See the HTTP cookie page.
- boolskipEncoding
Whether UniWebView should skip encoding the url or not. If set to
false
, UniWebView will try to encode the url parameter before using it. Otherwise, your original url string will be used to set the cookie if it is valid. Default isfalse
.
Example
// Set a cookie "testCookie=1" to current url/domain.
UniWebView.SetCookie(webView.Url, "testCookie=1");
// Set a full properties specified cookie.
UniWebView.SetCookie("https://example.com", "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT");
Gets the cookie value under a url and key.
- stringurl
The url (domain) where the target cookie is.
- stringkey
The key for target cookie value.
- boolskipEncoding
Whether UniWebView should skip encoding the url or not. If set to
false
, UniWebView will try to encode the url parameter before using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default isfalse
.
Value of the target cookie under url.
Example
UniWebView.GetCookie("https://example.com", "testCookie");
// => The corresponding cookie value. Or "" if there is no such cookie.
Clears any saved credentials for HTTP authentication for both Basic and Digest.
On both iOS and Android, the user input credentials will be stored permanently across the session. It could prevent your users to input username and password again until they changed. If you need the credentials only living in a shorter lifetime, call this method at proper timing.
On iOS, it will clear the credentials immediately and completely from both disk and network cache. On Android, it only clears from disk database, the authentication might be still cached in the network stack and will not be removed until next session (app restarting).
The client logout mechanism should be implemented by the Web site designer (such as server sending an HTTP 401 for invalidating credentials).
- stringhost
The host to which the credentials apply. It should not contain any thing like scheme or path part.
- stringrealm
The realm to which the credentials apply.
Example
UniWebView.ClearHttpAuthUsernamePassword("uniwebview.com", "UniWebViewUserRealm");
Sets whether to show a loading indicator while the loading is in progress.
- boolflag
Whether an indicator should show.
Sets the text displayed in the loading indicator, if SetShowSpinnerWhileLoading
is set to true
.
- stringtext
The text to display while loading indicator visible. Default is "Loading..."
Sets whether the horizontal scroll bar should show when the web content beyonds web view bounds.
This only works on mobile platforms. It will do nothing on macOS Editor.
- boolenabled
Whether enable the scroll bar or not.
Sets whether the vertical scroll bar should show when the web content beyonds web view bounds.
This only works on mobile platforms. It will do nothing on macOS Editor.
- boolenabled
Whether enable the scroll bar or not.
Sets whether the web view should show with a bounces effect when scrolling to page edge.
This only works on mobile platforms. It will do nothing on macOS Editor.
- boolenabled
Whether enable the bounces effect should be applied or not.
Sets whether the web view supports zoom gesture to change content size. Default is false
, which means the zoom gesture is not supported.
- boolenabled
Whether the zoom gesture is allowed or not.
Adds a trusted domain to white list and allow permission requests from the domain.
You only need this on Android devices with the system before 6.0 when a site needs the location or camera permission. It will allow the permission gets approved so you could access the corresponding devices. From Android 6.0, the permission requests method is changed and this is not needed anymore.
NOTICE
This method is not the same to AddSslExceptionDomain
,
which is for bypassing SSL checking. You only need this method when
you have trouble in granting users' permission. It is not needed on iOS.
- stringdomain
The domain to add to the white list.
Example
webView.AddPermissionTrustDomain("my-own-site.com");
Removes a trusted domain from white list.
- stringdomain
The domain to remove from white list.
Sets whether the device back button should be enabled to execute "go back" or "closing" operation.
On Android, the device back button in navigation bar will navigate users to a back page. If there is no any back page available, the back button clicking will try to raise an OnShouldClose
event and try to close the web view if true
is return from the event. If the OnShouldClose
event is not listened to, the web view will be closed and the UniWebView component will be destroyed to release any resource in use.
Listen to OnKeyCodeReceived
if you need to disable the back button, but still, want to get the back button key pressing event.
This method is only for Android. On iOS, you could show a toolbar with navigation and Done buttons for similar purpose.
The default is enabled.
- boolenabled
Whether the back button should perform go back or closing operation to web view.
Sets whether the web view should enable support for the "viewport" HTML meta tag or should use a wide viewport.
This method is only for Android. The default is disabled.
- boolflag
Whether to enable support for the viewport meta tag.
Sets whether the web view loads pages in overview mode, that is, zooms out the content to fit on screen by width.
This method is only for Android. The default is disabled.
- boolflag
Whether to enable support for the overview mode.
Sets whether the web view should behave in immersive mode, that is, hides the status bar and navigation bar with a sticky style.
If disabled, the navigation bar will always show up while the web view is visible.
This method is only for Android. The default is enabled.
- boolenabled
Whether to enable immersive mode when web view is showing up.
Sets whether to show a toolbar which contains navigation buttons and Done button.
You could choose to show or hide the toolbar. By configuring the animated
and onTop
parameters, you can control the animating and position of the toolbar. If the toolbar is overlapping with some part of your web view, pass adjustInset
with true
to have the web view relocating itself to avoid the overlap.
This method is only for iOS. The toolbar is hidden by default.
- boolshow
Whether the toolbar should show or hide.
- boolanimated
Whether the toolbar state changing should be with animation. Default is
false
. - boolopTop
Whether the toolbar should snap to top of screen or to bottom of screen. Default is
true
- booladjustInset
Whether the toolbar transition should also adjust web view position and size if overlapped. Default is
false
Example
// Show a toolbar at top of screen with animation.
webView.SetShowToolbar(true, true, true);
// Hide the tool bar without animation. At the same time, make
// the web view snap to screen top if there was overlapping between
// the web view and toolbar.
webView.SetShowToolbar(false, false, true, true);
Sets the done button text in toolbar.
By default, UniWebView will show a "Done" button at bottom-right corner in the toolbar. You could change its title by passing a text.
This method is only for iOS since there is no toolbar on Android.
- stringtext
The text needed to be set as done button title.
Example
webView.SetToolbarDoneButtonText("关闭");
Sets the visibility of navigation buttons, such as "Go Back" and "Go Forward", on toolbar.
By default, UniWebView will show the "Go Back" and "Go Forward" navigation buttons on the toolbar.
Users can use these buttons to perform go back or go forward action just like in a browser. If the navigation
model is not for your case, call this method with false
as show
parameter to hide them.
This method is only for iOS, since there is no toolbar on Android.
- boolshow
Whether the navigation buttons on the toolbar should show or hide.
Sets whether the web view can receive user interaction or not.
By setting this to false
, the web view will not accept any user touch event so your users cannot tap links or
scroll the page.
- boolenabled
Whether the user interaction should be enabled or not.
Enables debugging of web contents. You could inspect of the content of a web view by using a browser development tool of Chrome for Android or Safari for macOS.
This method is only for Android and macOS Editor. On iOS, you do not need an additional step. You could open Safari's developer tools to debug a web view on iOS.
NOTICE
Due to a memory bug under WebKit and Unity, it might crash your macOS Editor when you stop playing with an inspector showing embedded in a web view. You could close the inspector first or use it as a standalone window to avoid this. It will only happen in the editor and never affect real devices.
Please remember to disable this in your product build. This should be only used while development.
- boolenabled
Whether the content debugging should be enabled.
Enables user resizing for web view window. By default, you can only set the window size by setting its frame on mac Editor. By enabling user resizing, you would be able to resize the window by dragging its border as a normal macOS window.
NOTICE
This method only works for macOS for debugging purpose. It does nothing on iOS and Android.
- boolenabled
Whether the window could be able to be resized by the cursor.
Sets whether file access from file URLs is allowed.
By setting with true
, access to file URLs inside the web view will be enabled and you could access sub-resources or
make cross origin requests from local HTML files. This method only works on iOS. The file accessing from file URLs on
Android is available by default.
NOTICE
By setting allowing access from file URLs, you will bring some potential security issue to your app. Some malicious script would be able to read your sandbox. So we DO NOT recommend to enable it before you realize and understand the risk. UniWebView cannot provide any warranty on this security issue.
- boolflag
Whether the file access from file URLs is allowed or not.
Example
webView.SetAllowFileAccessFromFileURLs(true);
Sets whether a prompt alert should be displayed for collection username and password when the web view receives an HTTP authentication challenge (HTTP Basic or HTTP Digest) from server.
By setting with false
, no prompt will be shown and the user cannot login with input credentials. In this case,
you can only access this page by providing username and password through the URL like: "http://username:password@example.com".
If the username and password does not match, normally an error with 401 as status code would be returned (this behavior depends
on the server implementation). If set with true
, a prompt will be shown when there is no credentials provided or it is not
correct in the URL.
Default is true
.
- boolflag
Whether a prompt alert should be shown for HTTP authentication challenge or not.
Example
// This URL requires HTTP Basic authentication.
var url = "https://example.com/auth/http-basic";
// A prompt alert will be shown and user has a chance to input their username/password.
webView.Load(url);
// Setting to false, this will use "username" and "password" to response server challenge.
webView.SetAllowHTTPAuthPopUpWindow(false);
webView.Load("https://username:password@example.com/auth/http-basic");
// Loading a URL but not providing credentials and no chance for user to input.
// An error might be raised according to your server implementation.
webView.SetAllowHTTPAuthPopUpWindow(false);
webView.Load(url);
Gets the HTML content from current page by accessing its outerHTML
with JavaScript.
- Action<string>handler
Called after the JavaScript executed. The parameter
string
is the content read from page.
Example
webView.GetHTMLContent((content)=>{
print(content);
// => "<html><head> ... </html>"
});
Prints current page.
By calling this method, a native print preview panel will be brought up on iOS and Android. This method does nothing on macOS editor.
NOTICE
On iOS and Android, the web view does not support JavaScript (window.print()), you can only initialize a print job from Unity by this method.
Scrolls the web view to a certain point.
Use 0 for both x
and y
value to scroll the web view to its origin. In a normal vertical web page, it is equivalent as scrolling to top.
You can use the animated
parameter to control whether scrolling the page with or without animation.
This parameter only works on iOS and Android. On macOS editor, the scrolling always happens without animation.
- intx
X value of the target scrolling point.
- inty
Y value of the target scrolling point.
- boolanimated
If
true
, the scrolling happens with animation. Otherwise, it happens without animation and the content is set directly.
Example
// Scroll the web page to top with animation.
webView.ScrollTo(0, 0, true);