暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920
  1. //
  2. // UniWebView.cs
  3. // Created by Wang Wei (@onevcat) on 2017-04-11.
  4. //
  5. // This file is a part of UniWebView Project (https://uniwebview.com)
  6. // By purchasing the asset, you are allowed to use this code in as many as projects
  7. // you want, only if you publish the final products under the name of the same account
  8. // used for the purchase.
  9. //
  10. // This asset and all corresponding files (such as source code) are provided on an
  11. // “as is” basis, without warranty of any kind, express of implied, including but not
  12. // limited to the warranties of merchantability, fitness for a particular purpose, and
  13. // noninfringement. In no event shall the authors or copyright holders be liable for any
  14. // claim, damages or other liability, whether in action of contract, tort or otherwise,
  15. // arising from, out of or in connection with the software or the use of other dealing in the software.
  16. //
  17. using UnityEngine;
  18. using System.Collections;
  19. using System.Collections.Generic;
  20. using System;
  21. /// <summary>
  22. /// Main class of UniWebView. Any `GameObject` instance with this script can represent a webview object in the scene.
  23. /// Use this class to create, load, show and interact with a general-purpose web view.
  24. /// </summary>
  25. public class UniWebView: MonoBehaviour {
  26. /// <summary>
  27. /// Delegate for page started event.
  28. /// </summary>
  29. /// <param name="webView">The web view component which raises this event.</param>
  30. /// <param name="url">The url which the web view is about to load.</param>
  31. public delegate void PageStartedDelegate(UniWebView webView, string url);
  32. /// <summary>
  33. /// Raised when the web view starts loading a url.
  34. ///
  35. /// This event will be invoked for both url loading with `Load` method or by a link navigating from page.
  36. /// </summary>
  37. public event PageStartedDelegate OnPageStarted;
  38. /// <summary>
  39. /// Delegate for page finished event.
  40. /// </summary>
  41. /// <param name="webView">The web view component which raises this event.</param>
  42. /// <param name="statusCode">HTTP status code received from response.</param>
  43. /// <param name="url">The url which the web view loaded.</param>
  44. public delegate void PageFinishedDelegate(UniWebView webView, int statusCode, string url);
  45. /// <summary>
  46. /// Raised when the web view finished to load a url successfully.
  47. ///
  48. /// This method will be invoked when a valid response received from the url, regardless of the response status.
  49. /// If a url loading fails before reaching to the server and getting a response, `OnPageErrorReceived` will be
  50. /// raised instead.
  51. /// </summary>
  52. public event PageFinishedDelegate OnPageFinished;
  53. /// <summary>
  54. /// Delegate for page error received event.
  55. /// </summary>
  56. /// <param name="webView">The web view component which raises this event.</param>
  57. /// <param name="errorCode">
  58. /// The error code which indicates the error type.
  59. /// It can be different from systems and platforms.
  60. /// </param>
  61. /// <param name="errorMessage">The error message which indicates the error.</param>
  62. public delegate void PageErrorReceivedDelegate(UniWebView webView, int errorCode, string errorMessage);
  63. /// <summary>
  64. /// Raised when an error encountered during the loading process.
  65. /// Such as the "host not found" error or "no Internet connection" error will raise this event.
  66. /// </summary>
  67. public event PageErrorReceivedDelegate OnPageErrorReceived;
  68. /// <summary>
  69. /// Delegate for page progress changed event.
  70. /// </summary>
  71. /// <param name="webView">The web view component which raises this event.</param>
  72. /// <param name="progress">A value indicates the loading progress of current page. It is a value between 0.0f and 1.0f.</param>
  73. public delegate void PageProgressChangedDelegate(UniWebView webView, float progress);
  74. /// <summary>
  75. /// Raised when the loading progress value changes in current web view.
  76. /// </summary>
  77. public event PageProgressChangedDelegate OnPageProgressChanged;
  78. /// <summary>
  79. /// Delegate for message received event.
  80. /// </summary>
  81. /// <param name="webView">The web view component which raises this event.</param>
  82. /// <param name="message">Message received from web view.</param>
  83. public delegate void MessageReceivedDelegate(UniWebView webView, UniWebViewMessage message);
  84. /// <summary>
  85. /// Raised when a message from web view is received.
  86. ///
  87. /// Generally, the message comes from a navigation to
  88. /// a scheme which is observed by current web view. You could use `AddUrlScheme` and
  89. /// `RemoveUrlScheme` to manipulate the scheme list.
  90. ///
  91. /// "uniwebview://" scheme is default in the list, so a clicking on link starting with "uniwebview://"
  92. /// will raise this event, if it is not removed.
  93. /// </summary>
  94. public event MessageReceivedDelegate OnMessageReceived;
  95. /// <summary>
  96. /// Delegate for should close event.
  97. /// </summary>
  98. /// <param name="webView">The web view component which raises this event.</param>
  99. /// <returns>Whether the web view should be closed and destroyed.</returns>
  100. public delegate bool ShouldCloseDelegate(UniWebView webView);
  101. /// <summary>
  102. /// Raised when the web view is about to close itself.
  103. ///
  104. /// This event is raised when the users close the web view by Back button on Android, Done button on iOS,
  105. /// or Close button on Unity Editor. It gives a chance to make final decision whether the web view should
  106. /// be closed and destroyed. You can also clean all related resources you created (such as a reference to
  107. /// the web view) in this event.
  108. /// </summary>
  109. public event ShouldCloseDelegate OnShouldClose;
  110. /// <summary>
  111. /// Delegate for orientation changed event.
  112. /// </summary>
  113. /// <param name="webView">The web view component which raises this event.</param>
  114. /// <param name="orientation">The screen orientation for current state.</param>
  115. public delegate void OrientationChangedDelegate(UniWebView webView, ScreenOrientation orientation);
  116. /// <summary>
  117. /// Raised when the screen orientation is changed. It is a good time to set the web view frame if you
  118. /// need to support multiple orientations in your game.
  119. /// </summary>
  120. public event OrientationChangedDelegate OnOrientationChanged;
  121. /// <summary>
  122. /// Delegate for content loading terminated event.
  123. /// </summary>
  124. /// <param name="webView">The web view component which raises this event.</param>
  125. public delegate void OnWebContentProcessTerminatedDelegate(UniWebView webView);
  126. /// <summary>
  127. /// Raised when on iOS, when system calls `webViewWebContentProcessDidTerminate` method.
  128. /// It is usually due to a low memory when loading the web content and leave you a blank white screen.
  129. /// You need to free as much as memory you could and then do a page reload.
  130. /// </summary>
  131. public event OnWebContentProcessTerminatedDelegate OnWebContentProcessTerminated;
  132. /// <summary>
  133. /// Delegate for file download task starting event.
  134. /// </summary>
  135. /// <param name="webView">The web view component which raises this event.</param>
  136. /// <param name="remoteUrl">The remote URL of this download task. This is also the download URL for the task.</param>
  137. /// <param name="fileName">The file name which user chooses to use.</param>
  138. public delegate void FileDownloadStarted(UniWebView webView, string remoteUrl, string fileName);
  139. /// <summary>
  140. /// Raised when a file download task starts.
  141. /// </summary>
  142. public event FileDownloadStarted OnFileDownloadStarted;
  143. /// <summary>
  144. /// Delegate for file download task finishing event.
  145. /// </summary>
  146. /// <param name="webView">The web view component which raises this event.</param>
  147. /// <param name="errorCode">
  148. /// The error code of the download task result. Value `0` means the download finishes without a problem.
  149. /// Any other non-`0` value indicates an issue. The detail meaning of the error code depends on system.
  150. /// On iOS, it is usually the `errorCode` of the received `NSURLError`. On Android, the value usually represents
  151. /// an `ERROR_*` value in `DownloadManager`.
  152. /// </param>
  153. /// <param name="remoteUrl">The remote URL of this download task.</param>
  154. /// <param name="diskPath">
  155. /// The file path of the downloaded file. On iOS, the downloader file is in a temporary folder of your app sandbox.
  156. /// On Android, it is in the "Download" folder of your app.
  157. /// </param>
  158. public delegate void FileDownloadFinished(UniWebView webView, int errorCode, string remoteUrl, string diskPath);
  159. /// <summary>
  160. /// Raised when a file download task finishes with either an error or success.
  161. /// </summary>
  162. public event FileDownloadFinished OnFileDownloadFinished;
  163. /// <summary>
  164. /// Delegate for capturing snapshot finished event.
  165. /// </summary>
  166. /// <param name="webView">The web view component which raises this event.</param>
  167. /// <param name="errorCode">
  168. /// The error code of the event. If the snapshot is captured and stored without a problem, the error code is 0.
  169. /// Any other number indicates an error happened. In most cases, the screenshot capturing only fails due to lack
  170. /// of disk storage.
  171. /// </param>
  172. /// <param name="diskPath">
  173. /// An accessible disk path to the captured snapshot image. If an error happens, it is an empty string.
  174. /// </param>
  175. public delegate void CaptureSnapshotFinished(UniWebView webView, int errorCode, string diskPath);
  176. /// <summary>
  177. /// Raised when an image captured and stored in a cache path on disk.
  178. /// </summary>
  179. public event CaptureSnapshotFinished OnCaptureSnapshotFinished;
  180. /// <summary>
  181. /// Delegate for multiple window opening event.
  182. /// </summary>
  183. /// <param name="webView">The web view component which opens the new multiple (pop-up) window.</param>
  184. /// <param name="multipleWindowId">The identifier of the opened new window.</param>
  185. public delegate void MultipleWindowOpenedDelegate(UniWebView webView, string multipleWindowId);
  186. /// <summary>
  187. /// Raised when a new window is opened. This happens when you enable the `SetSupportMultipleWindows` and open a
  188. /// new pop-up window.
  189. /// </summary>
  190. public event MultipleWindowOpenedDelegate OnMultipleWindowOpened;
  191. /// <summary>
  192. /// Delegate for multiple window closing event.
  193. /// </summary>
  194. /// <param name="webView">The web view component which closes the multiple window.</param>
  195. /// <param name="multipleWindowId">The identifier of the closed window.</param>
  196. public delegate void MultipleWindowClosedDelegate(UniWebView webView, string multipleWindowId);
  197. /// <summary>
  198. /// Raised when the multiple window is closed. This happens when the pop-up window is closed by navigation operation
  199. /// or by a invocation of `close()` on the page.
  200. /// </summary>
  201. public event MultipleWindowClosedDelegate OnMultipleWindowClosed;
  202. private string id = Guid.NewGuid().ToString();
  203. private UniWebViewNativeListener listener;
  204. /// <summary>
  205. /// Represents the embedded toolbar in the current web view.
  206. /// </summary>
  207. public UniWebViewEmbeddedToolbar EmbeddedToolbar { get; private set; }
  208. private bool isPortrait;
  209. [SerializeField]
  210. #pragma warning disable 0649
  211. private string urlOnStart;
  212. [SerializeField]
  213. private bool showOnStart = false;
  214. [SerializeField]
  215. private bool fullScreen;
  216. [Obsolete("Use Toolbar is deprecated. Use the embedded toolbar instead.", false)]
  217. [SerializeField]
  218. private bool useToolbar;
  219. [Obsolete("Use Toolbar is deprecated. Use the embedded toolbar instead.", false)]
  220. [SerializeField]
  221. private UniWebViewToolbarPosition toolbarPosition;
  222. [SerializeField]
  223. private bool useEmbeddedToolbar;
  224. [SerializeField]
  225. private UniWebViewToolbarPosition embeddedToolbarPosition;
  226. #pragma warning restore 0649
  227. // Action callback holders
  228. private Dictionary<String, Action> actions = new Dictionary<String, Action>();
  229. private Dictionary<String, Action<UniWebViewNativeResultPayload>> payloadActions = new Dictionary<String, Action<UniWebViewNativeResultPayload>>();
  230. [SerializeField]
  231. private Rect frame;
  232. /// <summary>
  233. /// Gets or sets the frame of current web view. The value is based on current `Screen.width` and `Screen.height`.
  234. /// The first two values of `Rect` is `x` and `y` position and the followed two `width` and `height`.
  235. /// </summary>
  236. public Rect Frame {
  237. get { return frame; }
  238. set {
  239. frame = value;
  240. UpdateFrame();
  241. }
  242. }
  243. [SerializeField]
  244. private RectTransform referenceRectTransform;
  245. /// <summary>
  246. /// A reference rect transform which the web view should change its position and size to.
  247. /// Set it to a Unity UI element (which contains a `RectTransform`) under a canvas to determine
  248. /// the web view frame by a certain UI element.
  249. ///
  250. /// By using this, you could get benefit from [Multiple Resolutions UI](https://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html).
  251. ///
  252. /// </summary>
  253. public RectTransform ReferenceRectTransform {
  254. get {
  255. return referenceRectTransform;
  256. }
  257. set {
  258. referenceRectTransform = value;
  259. UpdateFrame();
  260. }
  261. }
  262. private bool started;
  263. private bool backButtonEnabled = true;
  264. /// <summary>
  265. /// The url of current loaded web page.
  266. /// </summary>
  267. public string Url {
  268. get { return UniWebViewInterface.GetUrl(listener.Name); }
  269. }
  270. /// <summary>
  271. /// Updates and sets current frame of web view to match the setting.
  272. ///
  273. /// This is useful if the `referenceRectTransform` is changed and you need to sync the frame change
  274. /// to the web view. This method follows the frame determining rules.
  275. /// </summary>
  276. public void UpdateFrame() {
  277. Rect rect = NextFrameRect();
  278. UniWebViewInterface.SetFrame(listener.Name, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
  279. }
  280. Rect NextFrameRect() {
  281. if (referenceRectTransform == null) {
  282. UniWebViewLogger.Instance.Info("Using Frame setting to determine web view frame.");
  283. return frame;
  284. } else {
  285. UniWebViewLogger.Instance.Info("Using reference RectTransform to determine web view frame.");
  286. var worldCorners = new Vector3[4];
  287. referenceRectTransform.GetWorldCorners(worldCorners);
  288. var bottomLeft = worldCorners[0];
  289. var topLeft = worldCorners[1];
  290. var topRight = worldCorners[2];
  291. var bottomRight = worldCorners[3];
  292. var canvas = referenceRectTransform.GetComponentInParent<Canvas>();
  293. if (canvas == null) {
  294. return frame;
  295. }
  296. switch (canvas.renderMode) {
  297. case RenderMode.ScreenSpaceOverlay:
  298. break;
  299. case RenderMode.ScreenSpaceCamera:
  300. case RenderMode.WorldSpace:
  301. var camera = canvas.worldCamera;
  302. if (camera == null) {
  303. UniWebViewLogger.Instance.Critical(@"You need a render camera
  304. or event camera to use RectTransform to determine correct
  305. frame for UniWebView.");
  306. UniWebViewLogger.Instance.Info("No camera found. Fall back to ScreenSpaceOverlay mode.");
  307. } else {
  308. bottomLeft = camera.WorldToScreenPoint(bottomLeft);
  309. topLeft = camera.WorldToScreenPoint(topLeft);
  310. topRight = camera.WorldToScreenPoint(topRight);
  311. bottomRight = camera.WorldToScreenPoint(bottomRight);
  312. }
  313. break;
  314. }
  315. float widthFactor = (float)UniWebViewInterface.NativeScreenWidth() / (float)Screen.width;
  316. float heightFactor = (float)UniWebViewInterface.NativeScreenHeight() / (float)Screen.height;
  317. float x = topLeft.x * widthFactor;
  318. float y = (Screen.height - topLeft.y) * heightFactor;
  319. float width = (bottomRight.x - topLeft.x) * widthFactor;
  320. float height = (topLeft.y - bottomRight.y) * heightFactor;
  321. return new Rect(x, y, width, height);
  322. }
  323. }
  324. void Awake() {
  325. var listenerObject = new GameObject(id);
  326. listener = listenerObject.AddComponent<UniWebViewNativeListener>();
  327. listenerObject.transform.parent = transform;
  328. listener.webView = this;
  329. UniWebViewNativeListener.AddListener(listener);
  330. EmbeddedToolbar = new UniWebViewEmbeddedToolbar(listener);
  331. Rect rect;
  332. if (fullScreen) {
  333. rect = new Rect(0, 0, Screen.width, Screen.height);
  334. } else {
  335. rect = NextFrameRect();
  336. }
  337. UniWebViewInterface.Init(listener.Name, (int)rect.x, (int)rect. y, (int)rect.width, (int)rect.height);
  338. isPortrait = Screen.height >= Screen.width;
  339. }
  340. void Start() {
  341. if (showOnStart) {
  342. Show();
  343. }
  344. if (useEmbeddedToolbar) {
  345. EmbeddedToolbar.SetPosition(embeddedToolbarPosition);
  346. EmbeddedToolbar.Show();
  347. }
  348. if (!string.IsNullOrEmpty(urlOnStart)) {
  349. Load(urlOnStart);
  350. }
  351. started = true;
  352. if (referenceRectTransform != null) {
  353. UpdateFrame();
  354. }
  355. }
  356. void Update() {
  357. var newIsPortrait = Screen.height >= Screen.width;
  358. if (isPortrait != newIsPortrait) {
  359. isPortrait = newIsPortrait;
  360. if (OnOrientationChanged != null) {
  361. OnOrientationChanged(this, Screen.orientation);
  362. }
  363. if (referenceRectTransform != null) {
  364. UpdateFrame();
  365. }
  366. }
  367. // Only the new input system is enabled. Related flags: https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Installation.html#enabling-the-new-input-backends
  368. //
  369. // The new input system is not handling touchscreen events nicely as the old one.
  370. // The gesture detection hangs out regularly. Wait for an improvement of Unity.
  371. // So we choose to use the old one whenever it is available.
  372. #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
  373. var backDetected = backButtonEnabled && UnityEngine.InputSystem.Keyboard.current.escapeKey.wasPressedThisFrame;
  374. #else
  375. var backDetected = backButtonEnabled && Input.GetKeyUp(KeyCode.Escape);
  376. #endif
  377. if (backDetected) {
  378. UniWebViewLogger.Instance.Info("Received Back button, handling GoBack or close web view.");
  379. if (CanGoBack) {
  380. GoBack();
  381. } else {
  382. InternalOnShouldClose();
  383. }
  384. }
  385. }
  386. void OnEnable() {
  387. if (started) {
  388. _Show(useAsync: true);
  389. }
  390. }
  391. void OnDisable() {
  392. if (started) {
  393. _Hide(useAsync: true);
  394. }
  395. }
  396. /// <summary>
  397. /// Whether the web view is supported in current runtime or not.
  398. ///
  399. /// On some certain Android customized builds, the manufacturer prefers not containing the web view package in the
  400. /// system or blocks the web view package from being installed. If this happens, using of any web view related APIs will
  401. /// throw a `MissingWebViewPackageException` exception.
  402. ///
  403. /// Use this method to check whether the web view is available on the current running system. If this parameter returns `false`,
  404. /// you should not use the web view.
  405. ///
  406. /// This property always returns `true` on other supported platforms, such as iOS or macOS editor. It only performs
  407. /// runtime checking on Android. On other not supported platforms such as Windows or Linux, it always returns `false`.
  408. /// </summary>
  409. /// <value>Returns `true` if web view is supported on the current platform. Otherwise, `false`.</value>
  410. public static bool IsWebViewSupported {
  411. get {
  412. #if UNITY_EDITOR_OSX
  413. return true;
  414. #elif UNITY_EDITOR
  415. return false;
  416. #elif UNITY_IOS
  417. return true;
  418. #elif UNITY_STANDALONE_OSX
  419. return true;
  420. #elif UNITY_ANDROID
  421. return UniWebViewInterface.IsWebViewSupported();
  422. #else
  423. return false;
  424. #endif
  425. }
  426. }
  427. /// <summary>
  428. /// Loads a url in current web view.
  429. /// </summary>
  430. /// <param name="url">The url to be loaded. This url should start with `http://` or `https://` scheme. You could even load a non-ascii url text if it is valid.</param>
  431. /// <param name="skipEncoding">
  432. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  433. /// loading it. Otherwise, your original url string will be used as the url if it is valid. Default is `false`.
  434. /// </param>
  435. /// <param name="readAccessURL">
  436. /// The URL to allow read access to. This parameter is only used when loading from the filesystem in iOS, and passed
  437. /// to `loadFileURL:allowingReadAccessToURL:` method of WebKit. By default, the parent folder of the `url` parameter will be read accessible.
  438. /// </param>
  439. public void Load(string url, bool skipEncoding = false, string readAccessURL = null) {
  440. UniWebViewInterface.Load(listener.Name, url, skipEncoding, readAccessURL);
  441. }
  442. /// <summary>
  443. /// Loads an HTML string in current web view.
  444. /// </summary>
  445. /// <param name="htmlString">The HTML string to use as the contents of the webpage.</param>
  446. /// <param name="baseUrl">The url to use as the page's base url.</param>
  447. /// <param name="skipEncoding">
  448. /// Whether UniWebView should skip encoding the baseUrl or not. If set to `false`, UniWebView will try to encode the baseUrl parameter before
  449. /// using it. Otherwise, your original url string will be used as the baseUrl if it is valid. Default is `false`.
  450. /// </param>
  451. public void LoadHTMLString(string htmlString, string baseUrl, bool skipEncoding = false) {
  452. UniWebViewInterface.LoadHTMLString(listener.Name, htmlString, baseUrl, skipEncoding);
  453. }
  454. /// <summary>
  455. /// Reloads the current page.
  456. /// </summary>
  457. public void Reload() {
  458. UniWebViewInterface.Reload(listener.Name);
  459. }
  460. /// <summary>
  461. /// Stops loading all resources on the current page.
  462. /// </summary>
  463. public void Stop() {
  464. UniWebViewInterface.Stop(listener.Name);
  465. }
  466. /// <summary>
  467. /// Gets whether there is a back page in the back-forward list that can be navigated to.
  468. /// </summary>
  469. public bool CanGoBack {
  470. get {
  471. return UniWebViewInterface.CanGoBack(listener.Name);
  472. }
  473. }
  474. /// <summary>
  475. /// Gets whether there is a forward page in the back-forward list that can be navigated to.
  476. /// </summary>
  477. public bool CanGoForward {
  478. get {
  479. return UniWebViewInterface.CanGoForward(listener.Name);
  480. }
  481. }
  482. /// <summary>
  483. /// Navigates to the back item in the back-forward list.
  484. /// </summary>
  485. public void GoBack() {
  486. UniWebViewInterface.GoBack(listener.Name);
  487. }
  488. /// <summary>
  489. /// Navigates to the forward item in the back-forward list.
  490. /// </summary>
  491. public void GoForward() {
  492. UniWebViewInterface.GoForward(listener.Name);
  493. }
  494. /// <summary>
  495. /// Sets whether the link clicking in the web view should open the page in an external browser.
  496. /// </summary>
  497. /// <param name="flag">The flag indicates whether a link should be opened externally.</param>
  498. public void SetOpenLinksInExternalBrowser(bool flag) {
  499. UniWebViewInterface.SetOpenLinksInExternalBrowser(listener.Name, flag);
  500. }
  501. /// <summary>
  502. /// Sets the web view visible on screen.
  503. ///
  504. /// If you pass `false` and `UniWebViewTransitionEdge.None` to the first two parameters, it means no animation will
  505. /// be applied when showing. So the `duration` parameter will not be taken into account. Otherwise, when
  506. /// either or both `fade` and `edge` set, the showing operation will be animated.
  507. ///
  508. /// Regardless of there is an animation or not, the `completionHandler` will be called if not `null` when the web
  509. /// view showing finishes.
  510. /// </summary>
  511. /// <param name="fade">Whether show with a fade in animation. Default is `false`.</param>
  512. /// <param name="edge">The edge from which the web view showing. It simulates a modal effect when showing a web view. Default is `UniWebViewTransitionEdge.None`.</param>
  513. /// <param name="duration">Duration of the showing animation. Default is `0.4f`.</param>
  514. /// <param name="completionHandler">Completion handler which will be called when showing finishes. Default is `null`.</param>
  515. /// <returns>A bool value indicates whether the showing operation started.</returns>
  516. public bool Show(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  517. float duration = 0.4f, Action completionHandler = null)
  518. {
  519. return _Show(fade, edge, duration, false, completionHandler);
  520. }
  521. public bool _Show(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  522. float duration = 0.4f, bool useAsync = false, Action completionHandler = null)
  523. {
  524. var identifier = Guid.NewGuid().ToString();
  525. var showStarted = UniWebViewInterface.Show(listener.Name, fade, (int)edge, duration, useAsync, identifier);
  526. if (showStarted && completionHandler != null) {
  527. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  528. if (hasAnimation) {
  529. actions.Add(identifier, completionHandler);
  530. } else {
  531. completionHandler();
  532. }
  533. }
  534. #pragma warning disable 618
  535. if (showStarted && useToolbar) {
  536. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  537. SetShowToolbar(true, false, top, fullScreen);
  538. }
  539. #pragma warning restore 618
  540. return showStarted;
  541. }
  542. /// <summary>
  543. /// Sets the web view invisible from screen.
  544. ///
  545. /// If you pass `false` and `UniWebViewTransitionEdge.None` to the first two parameters, it means no animation will
  546. /// be applied when hiding. So the `duration` parameter will not be taken into account. Otherwise, when either or
  547. /// both `fade` and `edge` set, the hiding operation will be animated.
  548. ///
  549. /// Regardless there is an animation or not, the `completionHandler` will be called if not `null` when the web view
  550. /// hiding finishes.
  551. /// </summary>
  552. /// <param name="fade">Whether hide with a fade in animation. Default is `false`.</param>
  553. /// <param name="edge">The edge from which the web view hiding. It simulates a modal effect when hiding a web view. Default is `UniWebViewTransitionEdge.None`.</param>
  554. /// <param name="duration">Duration of hiding animation. Default is `0.4f`.</param>
  555. /// <param name="completionHandler">Completion handler which will be called when hiding finishes. Default is `null`.</param>
  556. /// <returns>A bool value indicates whether the hiding operation started.</returns>
  557. public bool Hide(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  558. float duration = 0.4f, Action completionHandler = null)
  559. {
  560. return _Hide(fade, edge, duration, false, completionHandler);
  561. }
  562. public bool _Hide(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  563. float duration = 0.4f, bool useAsync = false, Action completionHandler = null)
  564. {
  565. var identifier = Guid.NewGuid().ToString();
  566. var hideStarted = UniWebViewInterface.Hide(listener.Name, fade, (int)edge, duration, useAsync, identifier);
  567. if (hideStarted && completionHandler != null) {
  568. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  569. if (hasAnimation) {
  570. actions.Add(identifier, completionHandler);
  571. } else {
  572. completionHandler();
  573. }
  574. }
  575. #pragma warning disable 618
  576. if (hideStarted && useToolbar) {
  577. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  578. SetShowToolbar(false, false, top, fullScreen);
  579. }
  580. #pragma warning restore 618
  581. return hideStarted;
  582. }
  583. /// <summary>
  584. /// Animates the web view from current position and size to another position and size.
  585. /// </summary>
  586. /// <param name="frame">The new `Frame` which the web view should be.</param>
  587. /// <param name="duration">Duration of the animation.</param>
  588. /// <param name="delay">Delay before the animation begins. Default is `0.0f`, which means the animation will start immediately.</param>
  589. /// <param name="completionHandler">Completion handler which will be called when animation finishes. Default is `null`.</param>
  590. /// <returns></returns>
  591. public bool AnimateTo(Rect frame, float duration, float delay = 0.0f, Action completionHandler = null) {
  592. var identifier = Guid.NewGuid().ToString();
  593. var animationStarted = UniWebViewInterface.AnimateTo(listener.Name,
  594. (int)frame.x, (int)frame.y, (int)frame.width, (int)frame.height, duration, delay, identifier);
  595. if (animationStarted) {
  596. this.frame = frame;
  597. if (completionHandler != null) {
  598. actions.Add(identifier, completionHandler);
  599. }
  600. }
  601. return animationStarted;
  602. }
  603. /// <summary>
  604. /// Adds a JavaScript to current page.
  605. /// </summary>
  606. /// <param name="jsString">The JavaScript code to add. It should be a valid JavaScript statement string.</param>
  607. /// <param name="completionHandler">Called when adding JavaScript operation finishes. Default is `null`.</param>
  608. public void AddJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  609. var identifier = Guid.NewGuid().ToString();
  610. UniWebViewInterface.AddJavaScript(listener.Name, jsString, identifier);
  611. if (completionHandler != null) {
  612. payloadActions.Add(identifier, completionHandler);
  613. }
  614. }
  615. /// <summary>
  616. /// Evaluates a JavaScript string on current page.
  617. /// </summary>
  618. /// <param name="jsString">The JavaScript string to evaluate.</param>
  619. /// <param name="completionHandler">Called when evaluating JavaScript operation finishes. Default is `null`.</param>
  620. public void EvaluateJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  621. var identifier = Guid.NewGuid().ToString();
  622. UniWebViewInterface.EvaluateJavaScript(listener.Name, jsString, identifier);
  623. if (completionHandler != null) {
  624. payloadActions.Add(identifier, completionHandler);
  625. }
  626. }
  627. /// <summary>
  628. /// Adds a url scheme to UniWebView message system interpreter.
  629. /// All following url navigation to this scheme will be sent as a message to UniWebView instead.
  630. /// </summary>
  631. /// <param name="scheme">The url scheme to add. It should not contain "://" part. You could even add "http" and/or
  632. /// "https" to prevent all resource loading on the page. "uniwebview" is added by default. Nothing will happen if
  633. /// you try to add a duplicated scheme.</param>
  634. public void AddUrlScheme(string scheme) {
  635. if (scheme == null) {
  636. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  637. return;
  638. }
  639. if (scheme.Contains("://")) {
  640. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  641. return;
  642. }
  643. UniWebViewInterface.AddUrlScheme(listener.Name, scheme);
  644. }
  645. /// <summary>
  646. /// Removes a url scheme from UniWebView message system interpreter.
  647. /// </summary>
  648. /// <param name="scheme">The url scheme to remove. Nothing will happen if the scheme is not in the message system.</param>
  649. public void RemoveUrlScheme(string scheme) {
  650. if (scheme == null) {
  651. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  652. return;
  653. }
  654. if (scheme.Contains("://")) {
  655. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  656. return;
  657. }
  658. UniWebViewInterface.RemoveUrlScheme(listener.Name, scheme);
  659. }
  660. /// <summary>
  661. /// Adds a domain to the SSL checking white list.
  662. /// If you are trying to access a web site with untrusted or expired certification,
  663. /// the web view will prevent its loading. If you could confirm that this site is trusted,
  664. /// you can add the domain as an SSL exception, so you could visit it.
  665. /// </summary>
  666. /// <param name="domain">The domain to add. It should not contain any scheme or path part in url.</param>
  667. public void AddSslExceptionDomain(string domain) {
  668. if (domain == null) {
  669. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  670. return;
  671. }
  672. if (domain.Contains("://")) {
  673. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  674. return;
  675. }
  676. UniWebViewInterface.AddSslExceptionDomain(listener.Name, domain);
  677. }
  678. /// <summary>
  679. /// Removes a domain from the SSL checking white list.
  680. /// </summary>
  681. /// <param name="domain">The domain to remove. It should not contain any scheme or path part in url.</param>
  682. public void RemoveSslExceptionDomain(string domain) {
  683. if (domain == null) {
  684. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  685. return;
  686. }
  687. if (domain.Contains("://")) {
  688. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  689. return;
  690. }
  691. UniWebViewInterface.RemoveSslExceptionDomain(listener.Name, domain);
  692. }
  693. /// <summary>
  694. /// Sets a customized header field for web view requests.
  695. ///
  696. /// The header field will be used for all subsequence request.
  697. /// Pass `null` as value to unset a header field.
  698. ///
  699. /// Some reserved headers like user agent are not be able to override by setting here,
  700. /// use the `SetUserAgent` method for them instead.
  701. /// </summary>
  702. /// <param name="key">The key of customized header field.</param>
  703. /// <param name="value">The value of customized header field. `null` if you want to unset the field.</param>
  704. public void SetHeaderField(string key, string value) {
  705. if (key == null) {
  706. UniWebViewLogger.Instance.Critical("Header key should not be null.");
  707. return;
  708. }
  709. UniWebViewInterface.SetHeaderField(listener.Name, key, value);
  710. }
  711. /// <summary>
  712. /// Sets the user agent used in the web view.
  713. /// If the string is null or empty, the system default value will be used.
  714. /// </summary>
  715. /// <param name="agent">The new user agent string to use.</param>
  716. public void SetUserAgent(string agent) {
  717. UniWebViewInterface.SetUserAgent(listener.Name, agent);
  718. }
  719. /// <summary>
  720. /// Gets the user agent string currently used in web view.
  721. /// If a customized user agent is not set, the default user agent in current platform will be returned.
  722. /// </summary>
  723. /// <returns>The user agent string in use.</returns>
  724. public string GetUserAgent() {
  725. return UniWebViewInterface.GetUserAgent(listener.Name);
  726. }
  727. /// <summary>
  728. /// Sets the adjustment behavior which indicates how safe area insets
  729. /// are added to the adjusted content inset. It is a wrapper of `contentInsetAdjustmentBehavior` on iOS.
  730. ///
  731. /// It only works on iOS 11 and above. You need to call this method as soon as you create a web view,
  732. /// before you call any other methods related to web view layout (like `Show` or `SetShowToolbar`).
  733. /// </summary>
  734. /// <param name="behavior">The behavior for determining the adjusted content offsets.</param>
  735. public void SetContentInsetAdjustmentBehavior(
  736. UniWebViewContentInsetAdjustmentBehavior behavior
  737. )
  738. {
  739. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  740. UniWebViewInterface.SetContentInsetAdjustmentBehavior(listener.Name, behavior);
  741. #endif
  742. }
  743. /// <summary>
  744. /// Sets allow auto play for current web view. By default,
  745. /// users need to touch the play button to start playing a media resource.
  746. ///
  747. /// By setting this to `true`, you can start the playing automatically through
  748. /// corresponding media tag attributes.
  749. /// </summary>
  750. /// <param name="flag">A flag indicates whether autoplaying of media is allowed or not.</param>
  751. public static void SetAllowAutoPlay(bool flag) {
  752. UniWebViewInterface.SetAllowAutoPlay(flag);
  753. }
  754. /// <summary>
  755. /// Sets allow inline play for current web view. By default, on iOS, the video
  756. /// can only be played in a new full screen view.
  757. /// By setting this to `true`, you could play a video inline the page, instead of opening
  758. /// a new full screen window.
  759. ///
  760. /// This only works for iOS and macOS Editor.
  761. /// On Android, you could play videos inline by default and calling this method does nothing.
  762. /// </summary>
  763. /// <param name="flag">A flag indicates whether inline playing of media is allowed or not.</param>
  764. public static void SetAllowInlinePlay(bool flag) {
  765. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  766. UniWebViewInterface.SetAllowInlinePlay(flag);
  767. #endif
  768. }
  769. /// <summary>
  770. /// Sets whether loading a local file is allowed.
  771. ///
  772. /// If set to `false`, any load from a file URL `file://` for `Load` method will be rejected and trigger an
  773. /// `OnPageErrorReceived` event. That means you cannot load a web page from any local file. If you are not going to
  774. /// load any local files, setting it to `false` helps to reduce the interface of web view and improve the security.
  775. ///
  776. /// By default, it is `true` and the local file URL loading is allowed.
  777. /// </summary>
  778. /// <param name="flag">Whether the local file access by web view loading is allowed or not.</param>
  779. public void SetAllowFileAccess(bool flag) {
  780. UniWebViewInterface.SetAllowFileAccess(listener.Name, flag);
  781. }
  782. /// <summary>
  783. /// Sets whether file access from file URLs is allowed.
  784. ///
  785. /// By setting with `true`, access to file URLs inside the web view will be enabled and you could access
  786. /// sub-resources or make cross origin requests from local HTML files.
  787. ///
  788. /// On iOS, it uses some "hidden" way by setting `allowFileAccessFromFileURLs` in config preferences for WebKit.
  789. /// So it is possible that it stops working in a future version.
  790. ///
  791. /// On Android, it sets the `WebSettings.setAllowFileAccessFromFileURLs` for the current web view.
  792. /// </summary>
  793. /// <param name="flag">Whether the file access inside web view from file URLs is allowed or not.</param>
  794. public void SetAllowFileAccessFromFileURLs(bool flag) {
  795. UniWebViewInterface.SetAllowFileAccessFromFileURLs(listener.Name, flag);
  796. }
  797. /// <summary>
  798. /// Sets whether the UniWebView should allow third party cookies to be set. By default, on Android, the third party
  799. /// cookies are disallowed due to security reason. Setting this to `true` will allow the cookie manager to accept
  800. /// third party cookies you set.
  801. ///
  802. /// This method only works for Android. On iOS, this method does nothing and the third party cookies are always
  803. /// allowed.
  804. /// </summary>
  805. /// <param name="flag">Whether the third party cookies should be allowed.</param>
  806. public void SetAcceptThirdPartyCookies(bool flag) {
  807. #if UNITY_ANDROID && !UNITY_EDITOR
  808. UniWebViewInterface.SetAcceptThirdPartyCookies(listener.Name, flag);
  809. #endif
  810. }
  811. /// <summary>
  812. /// Sets allow universal access from file URLs. By default, on iOS, the `WKWebView` forbids any load of local files
  813. /// through AJAX even when opening a local HTML file. It checks the CORS rules and fails at web view level.
  814. /// This is useful when you want access these files by setting the `allowUniversalAccessFromFileURLs` key of web view
  815. /// configuration.
  816. ///
  817. /// On iOS and macOS Editor. It uses some "hidden" way by setting `allowUniversalAccessFromFileURLs` in config
  818. /// for WebKit. So it is possible that it stops working in a future version.
  819. ///
  820. /// On Android, it sets the `WebSettings.setAllowUniversalAccessFromFileURLs` and any later-created web views uses
  821. /// that value.
  822. /// </summary>
  823. /// <param name="flag">A flag indicates whether the universal access for files are allowed or not.</param>
  824. public static void SetAllowUniversalAccessFromFileURLs(bool flag) {
  825. UniWebViewInterface.SetAllowUniversalAccessFromFileURLs(flag);
  826. }
  827. /// <summary>
  828. /// Sets whether the web view area should avoid soft keyboard. It `true`, when the keyboard shows up, the web views
  829. /// content view will resize itself to avoid keyboard overlap the web content. Otherwise, the web view will not resize
  830. /// and just leave the content below under the soft keyboard.
  831. ///
  832. /// This method is only for Android. On iOS, the keyboard avoidance is built into the system directly and there is
  833. /// no way to change its behavior.
  834. /// </summary>
  835. /// <param name="flag">Whether the keyboard should avoid web view content.</param>
  836. public static void SetEnableKeyboardAvoidance(bool flag) {
  837. #if UNITY_ANDROID && !UNITY_EDITOR
  838. UniWebViewInterface.SetEnableKeyboardAvoidance(flag);
  839. #endif
  840. }
  841. /// <summary>
  842. /// Sets whether JavaScript should be enabled in current web view. Default is enabled.
  843. /// </summary>
  844. /// <param name="enabled">Whether JavaScript should be enabled.</param>
  845. public static void SetJavaScriptEnabled(bool enabled) {
  846. UniWebViewInterface.SetJavaScriptEnabled(enabled);
  847. }
  848. /// <summary>
  849. /// Sets whether the web view limits navigation to pages within the app’s domain.
  850. ///
  851. /// This only works on iOS 14.0+. For more information, refer to the Apple's documentation:
  852. /// https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/3585117-limitsnavigationstoappbounddomai
  853. /// and the App-Bound Domains page: https://webkit.org/blog/10882/app-bound-domains/
  854. ///
  855. /// This requires additional setup in `WKAppBoundDomains` key in the Info.plist file.
  856. ///
  857. /// On Android, this method does nothing.
  858. /// </summary>
  859. /// <param name="enabled"></param>
  860. public static void SetLimitsNavigationsToAppBoundDomains(bool enabled) {
  861. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  862. UniWebViewInterface.SetLimitsNavigationsToAppBoundDomains(enabled);
  863. #endif
  864. }
  865. /// <summary>
  866. /// Sets whether JavaScript can open windows without user interaction.
  867. ///
  868. /// By setting this to `true`, an automatically JavaScript navigation will be allowed in the web view.
  869. /// </summary>
  870. /// <param name="flag">Whether JavaScript could open window automatically.</param>
  871. public static void SetAllowJavaScriptOpenWindow(bool flag) {
  872. UniWebViewInterface.SetAllowJavaScriptOpenWindow(flag);
  873. }
  874. /// <summary>
  875. /// Cleans web view cache. This removes cached local data of web view.
  876. ///
  877. /// If you need to clear all cookies, use `ClearCookies` instead.
  878. /// </summary>
  879. public void CleanCache() {
  880. UniWebViewInterface.CleanCache(listener.Name);
  881. }
  882. /// <summary>
  883. /// Clears all cookies from web view.
  884. ///
  885. /// This will clear cookies from all domains in the web view and previous.
  886. /// If you only need to remove cookies from a certain domain, use `SetCookie` instead.
  887. /// </summary>
  888. public static void ClearCookies() {
  889. UniWebViewInterface.ClearCookies();
  890. }
  891. /// <summary>
  892. /// Sets a cookie for a certain url.
  893. /// </summary>
  894. /// <param name="url">The url to which cookie will be set.</param>
  895. /// <param name="cookie">The cookie string to set.</param>
  896. /// <param name="skipEncoding">
  897. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  898. /// using it. Otherwise, your original url string will be used to set the cookie if it is valid. Default is `false`.
  899. /// </param>
  900. public static void SetCookie(string url, string cookie, bool skipEncoding = false) {
  901. UniWebViewInterface.SetCookie(url, cookie, skipEncoding);
  902. }
  903. /// <summary>
  904. /// Gets the cookie value under a url and key.
  905. /// </summary>
  906. /// <param name="url">The url (domain) where the target cookie is.</param>
  907. /// <param name="key">The key for target cookie value.</param>
  908. /// <param name="skipEncoding">
  909. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  910. /// using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default is `false`.
  911. /// </param>
  912. /// <returns>Value of the target cookie under url.</returns>
  913. public static string GetCookie(string url, string key, bool skipEncoding = false) {
  914. return UniWebViewInterface.GetCookie(url, key, skipEncoding);
  915. }
  916. /// <summary>
  917. /// Removes all the cookies under a url.
  918. /// </summary>
  919. /// <param name="url">The url (domain) where the cookies is under.</param>
  920. /// <param name="skipEncoding">
  921. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  922. /// using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default is `false`.
  923. /// </param>
  924. public static void RemoveCookies(string url, bool skipEncoding = false) {
  925. UniWebViewInterface.RemoveCookies(url, skipEncoding);
  926. }
  927. /// <summary>
  928. /// Removes the certain cookie under a url for the specified key.
  929. /// </summary>
  930. /// <param name="url">The url (domain) where the cookies is under.</param>
  931. /// <param name="key">The key for target cookie.</param>
  932. /// <param name="skipEncoding">
  933. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  934. /// using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default is `false`.
  935. /// </param>
  936. public static void RemoveCooke(string url, string key, bool skipEncoding = false) {
  937. UniWebViewInterface.RemoveCookie(url, key, skipEncoding);
  938. }
  939. /// <summary>
  940. /// Clears any saved credentials for HTTP authentication for both Basic and Digest.
  941. ///
  942. /// On both iOS and Android, the user input credentials will be stored permanently across session.
  943. /// It could prevent your users to input username and password again until they changed. If you need the
  944. /// credentials only living in a shorter lifetime, call this method at proper timing.
  945. ///
  946. /// On iOS, it will clear the credentials immediately and completely from both disk and network cache.
  947. /// On Android, it only clears from disk database, the authentication might be still cached in the network stack
  948. /// and will not be removed until next session (app restarting).
  949. ///
  950. /// The client logout mechanism should be implemented by the Web site designer (such as server sending a HTTP
  951. /// 401 for invalidating credentials).
  952. ///
  953. /// </summary>
  954. /// <param name="host">The host to which the credentials apply. It should not contain any thing like scheme or path part.</param>
  955. /// <param name="realm">The realm to which the credentials apply.</param>
  956. public static void ClearHttpAuthUsernamePassword(string host, string realm) {
  957. UniWebViewInterface.ClearHttpAuthUsernamePassword(host, realm);
  958. }
  959. private Color backgroundColor = Color.white;
  960. /// <summary>
  961. /// Gets or sets the background color of web view. The default value is `Color.white`.
  962. /// </summary>
  963. public Color BackgroundColor {
  964. get {
  965. return backgroundColor;
  966. }
  967. set {
  968. backgroundColor = value;
  969. UniWebViewInterface.SetBackgroundColor(listener.Name, value.r, value.g, value.b, value.a);
  970. }
  971. }
  972. /// <summary>
  973. /// Gets or sets the alpha value of the whole web view.
  974. ///
  975. /// You can make the game scene behind web view visible to make the web view transparent.
  976. ///
  977. /// Default is `1.0f`, which means totally opaque. Set it to `0.0f` will make the web view totally transparent.
  978. /// </summary>
  979. public float Alpha {
  980. get {
  981. return UniWebViewInterface.GetWebViewAlpha(listener.Name);
  982. }
  983. set {
  984. UniWebViewInterface.SetWebViewAlpha(listener.Name, value);
  985. }
  986. }
  987. /// <summary>
  988. /// Sets whether to show a loading indicator while the loading is in progress.
  989. /// </summary>
  990. /// <param name="flag">Whether an indicator should show.</param>
  991. public void SetShowSpinnerWhileLoading(bool flag) {
  992. UniWebViewInterface.SetShowSpinnerWhileLoading(listener.Name, flag);
  993. }
  994. /// <summary>
  995. /// Sets the text displayed in the loading indicator, if `SetShowSpinnerWhileLoading` is set to `true`.
  996. /// </summary>
  997. /// <param name="text">The text to display while loading indicator visible. Default is "Loading..."</param>
  998. public void SetSpinnerText(string text) {
  999. UniWebViewInterface.SetSpinnerText(listener.Name, text);
  1000. }
  1001. /// <summary>
  1002. /// Sets whether the user can dismiss the loading indicator by tapping on it or the greyed-out background around.
  1003. ///
  1004. /// By default, when the loading spinner is shown, the user can dismiss it by a single tapping. Call this method
  1005. /// with `false` to disable this behavior.
  1006. /// </summary>
  1007. /// <param name="flag">Whether the user can dismiss the loading indicator.</param>
  1008. public void SetAllowUserDismissSpinner(bool flag) {
  1009. UniWebViewInterface.SetAllowUserDismissSpinnerByGesture(listener.Name, flag);
  1010. }
  1011. /// <summary>
  1012. /// Shows the loading spinner.
  1013. ///
  1014. /// Calling this method will show the loading spinner, regardless if the `SetShowSpinnerWhileLoading` is set to
  1015. /// `true` or `false`. However, if `SetShowSpinnerWhileLoading` was called with `true`, UniWebView will still hide
  1016. /// the spinner when the loading finishes.
  1017. /// </summary>
  1018. public void ShowSpinner() {
  1019. UniWebViewInterface.ShowSpinner(listener.Name);
  1020. }
  1021. /// <summary>
  1022. /// Hides the loading spinner.
  1023. ///
  1024. /// Calling this method will hide the loading spinner, regardless if the `SetShowSpinnerWhileLoading` is set to
  1025. /// `true` or `false`. However, if `SetShowSpinnerWhileLoading` was called with `false`, UniWebView will still show
  1026. /// the spinner when the loading starts.
  1027. /// </summary>
  1028. public void HideSpinner() {
  1029. UniWebViewInterface.HideSpinner(listener.Name);
  1030. }
  1031. /// <summary>
  1032. /// Sets whether the horizontal scroll bar should show when the web content beyonds web view bounds.
  1033. ///
  1034. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  1035. /// </summary>
  1036. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  1037. public void SetHorizontalScrollBarEnabled(bool enabled) {
  1038. UniWebViewInterface.SetHorizontalScrollBarEnabled(listener.Name, enabled);
  1039. }
  1040. /// <summary>
  1041. /// Sets whether the vertical scroll bar should show when the web content beyonds web view bounds.
  1042. ///
  1043. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  1044. /// </summary>
  1045. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  1046. public void SetVerticalScrollBarEnabled(bool enabled) {
  1047. UniWebViewInterface.SetVerticalScrollBarEnabled(listener.Name, enabled);
  1048. }
  1049. /// <summary>
  1050. /// Sets whether the web view should show with a bounces effect when scrolling to page edge.
  1051. ///
  1052. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  1053. /// </summary>
  1054. /// <param name="enabled">Whether the bounces effect should be applied or not.</param>
  1055. public void SetBouncesEnabled(bool enabled) {
  1056. UniWebViewInterface.SetBouncesEnabled(listener.Name, enabled);
  1057. }
  1058. /// <summary>
  1059. /// Sets whether the web view supports zoom gesture to change content size.
  1060. /// Default is `false`, which means the zoom gesture is not supported.
  1061. /// </summary>
  1062. /// <param name="enabled">Whether the zoom gesture is allowed or not.</param>
  1063. public void SetZoomEnabled(bool enabled) {
  1064. UniWebViewInterface.SetZoomEnabled(listener.Name, enabled);
  1065. }
  1066. /// <summary>
  1067. /// Adds a trusted domain to white list and allow permission requests from the domain.
  1068. ///
  1069. /// You only need this on Android devices with system before 6.0 when a site needs the location or camera
  1070. /// permission. It will allow the permission gets approved so you could access the corresponding devices.
  1071. /// From Android 6.0, the permission requests method is changed and this is not needed anymore.
  1072. /// </summary>
  1073. /// <param name="domain">The domain to add to the white list.</param>
  1074. public void AddPermissionTrustDomain(string domain) {
  1075. #if UNITY_ANDROID && !UNITY_EDITOR
  1076. UniWebViewInterface.AddPermissionTrustDomain(listener.Name, domain);
  1077. #endif
  1078. }
  1079. /// <summary>
  1080. /// Removes a trusted domain from white list.
  1081. /// </summary>
  1082. /// <param name="domain">The domain to remove from white list.</param>
  1083. public void RemovePermissionTrustDomain(string domain) {
  1084. #if UNITY_ANDROID && !UNITY_EDITOR
  1085. UniWebViewInterface.RemovePermissionTrustDomain(listener.Name, domain);
  1086. #endif
  1087. }
  1088. /// <summary>
  1089. /// Sets whether the device back button should be enabled to execute "go back" or "closing" operation.
  1090. ///
  1091. /// On Android, the device back button in navigation bar will navigate users to a back page. If there is
  1092. /// no any back page avaliable, the back button clicking will try to raise a `OnShouldClose` event and try
  1093. /// to close the web view if `true` is return from the event. If the `OnShouldClose` is not listened,
  1094. /// the web view will be closed and the UniWebView component will be destroyed to release using resource.
  1095. ///
  1096. /// Listen to `OnKeyCodeReceived` if you need to disable the back button, but still want to get the back
  1097. /// button key pressing event.
  1098. ///
  1099. /// Default is enabled.
  1100. /// </summary>
  1101. /// <param name="enabled">Whether the back button should perform go back or closing operation to web view.</param>
  1102. public void SetBackButtonEnabled(bool enabled) {
  1103. this.backButtonEnabled = enabled;
  1104. }
  1105. /// <summary>
  1106. /// Sets whether the web view should enable support for the "viewport" HTML meta tag or should use a wide viewport.
  1107. /// </summary>
  1108. /// <param name="flag">Whether to enable support for the viewport meta tag.</param>
  1109. public void SetUseWideViewPort(bool flag) {
  1110. #if UNITY_ANDROID && !UNITY_EDITOR
  1111. UniWebViewInterface.SetUseWideViewPort(listener.Name, flag);
  1112. #endif
  1113. }
  1114. /// <summary>
  1115. /// Sets whether the web view loads pages in overview mode, that is, zooms out the content to fit on screen by width.
  1116. ///
  1117. /// This method is only for Android. Default is disabled.
  1118. /// </summary>
  1119. /// <param name="flag"></param>
  1120. public void SetLoadWithOverviewMode(bool flag) {
  1121. #if UNITY_ANDROID && !UNITY_EDITOR
  1122. UniWebViewInterface.SetLoadWithOverviewMode(listener.Name, flag);
  1123. #endif
  1124. }
  1125. /// <summary>
  1126. /// Sets whether to show a toolbar which contains navigation buttons and Done button.
  1127. ///
  1128. /// You could choose to show or hide the tool bar. By configuring the `animated` and `onTop`
  1129. /// parameters, you can control the animating and position of the toolbar. If the toolbar is
  1130. /// overlapping with some part of your web view, pass `adjustInset` with `true` to have the
  1131. /// web view relocating itself to avoid the overlap.
  1132. ///
  1133. /// This method is only for iOS. The toolbar is hidden by default.
  1134. /// </summary>
  1135. /// <param name="show">Whether the toolbar should show or hide.</param>
  1136. /// <param name="animated">Whether the toolbar state changing should be with animation. Default is `false`.</param>
  1137. /// <param name="onTop">Whether the toolbar should snap to top of screen or to bottom of screen.
  1138. /// Default is `true`</param>
  1139. /// <param name="adjustInset">Whether the toolbar transition should also adjust web view position and size
  1140. /// if overlapped. Default is `false`</param>
  1141. public void SetShowToolbar(bool show, bool animated = false, bool onTop = true, bool adjustInset = false) {
  1142. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1143. UniWebViewInterface.SetShowToolbar(listener.Name, show, animated, onTop, adjustInset);
  1144. #endif
  1145. }
  1146. /// <summary>
  1147. /// Sets the done button text in toolbar.
  1148. ///
  1149. /// By default, UniWebView will show a "Done" button at right size in the
  1150. /// toolbar. You could change its title by passing a text.
  1151. ///
  1152. /// This method is only for iOS, since there is no toolbar on Android.
  1153. /// </summary>
  1154. /// <param name="text">The text needed to be set as done button title.</param>
  1155. public void SetToolbarDoneButtonText(string text) {
  1156. #if UNITY_IOS && !UNITY_EDITOR
  1157. UniWebViewInterface.SetToolbarDoneButtonText(listener.Name, text);
  1158. #endif
  1159. }
  1160. /// <summary>
  1161. /// Sets the go back button text in toolbar.
  1162. ///
  1163. /// By default, UniWebView will show a back arrow at the left side in the
  1164. /// toolbar. You could change its text.
  1165. ///
  1166. /// This method is only for iOS and macOS Editor, since there is no toolbar on Android.
  1167. /// </summary>
  1168. /// <param name="text">The text needed to be set as go back button.</param>
  1169. public void SetToolbarGoBackButtonText(string text) {
  1170. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1171. UniWebViewInterface.SetToolbarGoBackButtonText(listener.Name, text);
  1172. #endif
  1173. }
  1174. /// <summary>
  1175. /// Sets the go forward button text in toolbar.
  1176. ///
  1177. /// By default, UniWebView will show a forward arrow at the left side in the
  1178. /// toolbar. You could change its text.
  1179. ///
  1180. /// This method is only for iOS and macOS Editor, since there is no toolbar on Android.
  1181. /// </summary>
  1182. /// <param name="text">The text needed to be set as go forward button.</param>
  1183. public void SetToolbarGoForwardButtonText(string text) {
  1184. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1185. UniWebViewInterface.SetToolbarGoForwardButtonText(listener.Name, text);
  1186. #endif
  1187. }
  1188. /// <summary>
  1189. /// Sets the background tint color for the toolbar.
  1190. ///
  1191. /// By default, UniWebView uses a default half-transparent iOS standard background for toolbar.
  1192. /// You can change it by setting a new opaque color.
  1193. ///
  1194. /// This method is only for iOS, since there is no toolbar on Android.
  1195. /// </summary>
  1196. /// <param name="color">The color should be used for the background tint of the toolbar.</param>
  1197. public void SetToolbarTintColor(Color color) {
  1198. #if UNITY_IOS && !UNITY_EDITOR
  1199. UniWebViewInterface.SetToolbarTintColor(listener.Name, color.r, color.g, color.b);
  1200. #endif
  1201. }
  1202. /// <summary>
  1203. /// Sets the button text color for the toolbar.
  1204. ///
  1205. /// By default, UniWebView uses the default text color on iOS, which is blue for most cases.
  1206. /// You can change it by setting a new opaque color.
  1207. ///
  1208. /// This method is only for iOS, since there is no toolbar on Android.
  1209. /// </summary>
  1210. /// <param name="color">The color should be used for the button text of the toolbar.</param>
  1211. public void SetToolbarTextColor(Color color) {
  1212. #if UNITY_IOS && !UNITY_EDITOR
  1213. UniWebViewInterface.SetToolbarTextColor(listener.Name, color.r, color.g, color.b);
  1214. #endif
  1215. }
  1216. /// <summary>
  1217. /// Sets the visibility of navigation buttons, such as "Go Back" and "Go Forward", on toolbar.
  1218. ///
  1219. /// By default, UniWebView will show the "Go Back" and "Go Forward" navigation buttons on the toolbar.
  1220. /// Users can use these buttons to perform go back or go forward action just like in a browser. If the navigation
  1221. /// model is not for your case, call this method with `false` as `show` parameter to hide them.
  1222. ///
  1223. /// This method is only for iOS, since there is no toolbar on Android.
  1224. /// </summary>
  1225. /// <param name="show">Whether the navigation buttons on the toolbar should show or hide.</param>
  1226. public void SetShowToolbarNavigationButtons(bool show) {
  1227. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1228. UniWebViewInterface.SetShowToolbarNavigationButtons(listener.Name, show);
  1229. #endif
  1230. }
  1231. /// <summary>
  1232. /// Sets whether the web view can receive user interaction or not.
  1233. ///
  1234. /// By setting this to `false`, the web view will not accept any user touch event so your users cannot tap links or
  1235. /// scroll the page.
  1236. ///
  1237. /// </summary>
  1238. /// <param name="enabled">Whether the user interaction should be enabled or not.</param>
  1239. public void SetUserInteractionEnabled(bool enabled) {
  1240. UniWebViewInterface.SetUserInteractionEnabled(listener.Name, enabled);
  1241. }
  1242. /// <summary>
  1243. /// Sets whether the web view should pass through clicks at clear pixels to Unity scene.
  1244. ///
  1245. /// Setting this method is a pre-condition for the whole passing-through feature to work. To allow your touch passing through
  1246. /// to Unity scene, the following conditions should be met at the same time:
  1247. ///
  1248. /// 1. This method is called with `true` and the web view accepts passing-through clicks.
  1249. /// 2. The web view has a transparent background in body style for its content by CSS.
  1250. /// 3. The web view itself has a transparent background color by setting `BackgroundColor` with a clear color.
  1251. ///
  1252. /// Then, when user clicks on the clear pixel on the web view, the touch events will not be handled by the web view.
  1253. /// Instead, these events are passed to Unity scene. By using this feature, it is possible to create a native UI with the
  1254. /// web view.
  1255. ///
  1256. /// Only clicks on transparent part on the web view will be delivered to Unity scene. The web view still intercepts
  1257. /// and handles other touches on visible pixels on the web view.
  1258. /// </summary>
  1259. /// <param name="enabled">Whether the transparency clicking through feature should be enabled in this web view.</param>
  1260. public void SetTransparencyClickingThroughEnabled(bool enabled) {
  1261. UniWebViewInterface.SetTransparencyClickingThroughEnabled(listener.Name, enabled);
  1262. }
  1263. /// <summary>
  1264. /// Enables debugging of web contents. You could inspect of the content of a
  1265. /// web view by using a browser development tool of Chrome for Android or Safari for macOS.
  1266. ///
  1267. /// This method is only for Android and macOS Editor. On iOS, you do not need additional step.
  1268. /// You could open Safari's developer tools to debug a web view on iOS.
  1269. /// </summary>
  1270. /// <param name="enabled">Whether the content debugging should be enabled.</param>
  1271. public static void SetWebContentsDebuggingEnabled(bool enabled) {
  1272. UniWebViewInterface.SetWebContentsDebuggingEnabled(enabled);
  1273. }
  1274. /// <summary>
  1275. /// Enables user resizing for web view window. By default, you can only set the window size
  1276. /// by setting its frame on mac Editor. By enabling user resizing, you would be able to resize
  1277. /// the window by dragging its border as a normal macOS window.
  1278. ///
  1279. /// This method only works for macOS for debugging purpose. It does nothing on iOS and Android.
  1280. /// </summary>
  1281. /// <param name="enabled">Whether the window could be able to be resized by cursor.</param>
  1282. public void SetWindowUserResizeEnabled(bool enabled) {
  1283. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1284. UniWebViewInterface.SetWindowUserResizeEnabled(listener.Name, enabled);
  1285. #endif
  1286. }
  1287. /// <summary>
  1288. /// Gets the HTML content from current page by accessing its outerHTML with JavaScript.
  1289. /// </summary>
  1290. /// <param name="handler">Called after the JavaScript executed. The parameter string is the content read
  1291. /// from page.</param>
  1292. public void GetHTMLContent(Action<string> handler) {
  1293. EvaluateJavaScript("document.documentElement.outerHTML", payload => {
  1294. if (handler != null) {
  1295. handler(payload.data);
  1296. }
  1297. });
  1298. }
  1299. /// <summary>
  1300. /// Sets whether horizontal swipe gestures should trigger back-forward list navigation.
  1301. ///
  1302. /// By setting with `true`, users can swipe from screen edge to perform a back or forward navigation.
  1303. /// This method only works on iOS and macOS Editor. Default is `false`.
  1304. ///
  1305. /// On Android, the screen navigation gestures are simulating the traditional back button and it is enabled by
  1306. /// default. To disable gesture navigation on Android, you have to also disable the device back button. See
  1307. /// `SetBackButtonEnabled` for that purpose.
  1308. /// </summary>
  1309. /// <param name="flag">
  1310. /// The value indicates whether a swipe gestures driven navigation should be allowed. Default is `false`.
  1311. /// </param>
  1312. public void SetAllowBackForwardNavigationGestures(bool flag) {
  1313. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1314. UniWebViewInterface.SetAllowBackForwardNavigationGestures(listener.Name, flag);
  1315. #endif
  1316. }
  1317. /// <summary>
  1318. /// Sets whether a prompt alert should be displayed for collection username and password when the web view receives an
  1319. /// HTTP authentication challenge (HTTP Basic or HTTP Digest) from server.
  1320. ///
  1321. /// By setting with `false`, no prompt will be shown and the user cannot login with input credentials. In this case,
  1322. /// you can only access this page by providing username and password through the URL like: "http://username:password@example.com".
  1323. /// If the username and password does not match, normally an error with 401 as status code would be returned (this behavior depends
  1324. /// on the server implementation). If set with `true`, a prompt will be shown when there is no credentials provided or it is not
  1325. /// correct in the URL.
  1326. ///
  1327. /// Default is `true`.
  1328. /// </summary>
  1329. /// <param name="flag">Whether a prompt alert should be shown for HTTP authentication challenge or not.</param>
  1330. public void SetAllowHTTPAuthPopUpWindow(bool flag) {
  1331. UniWebViewInterface.SetAllowHTTPAuthPopUpWindow(listener.Name, flag);
  1332. }
  1333. /// <summary>
  1334. /// Sets whether a callout (context) menu should be displayed when user long tapping on certain web view content.
  1335. ///
  1336. /// When enabled, when user long presses an image or link in the web page, a context menu would be show up to ask
  1337. /// user's action. On iOS, it is a action sheet to ask whether opening the target link or saving the image. On
  1338. /// Android it is a pop up dialog to ask whether saving the image to local disk. On iOS, the preview page triggered
  1339. /// by force touch on iOS is also considered as a callout menu.
  1340. ///
  1341. /// Default is `true`, means that the callout menu will be displayed. Call this method with `false` to disable
  1342. /// it on the web view.
  1343. /// </summary>
  1344. /// <param name="enabled">
  1345. /// Whether a callout menu should be displayed when user long pressing or force touching a certain web page element.
  1346. /// </param>
  1347. public void SetCalloutEnabled(bool enabled) {
  1348. UniWebViewInterface.SetCalloutEnabled(listener.Name, enabled);
  1349. }
  1350. [ObsoleteAttribute("Deprecated. Use `SetSupportMultipleWindows(bool enabled, bool allowJavaScriptOpen)` to set `allowJavaScriptOpen` explicitly.")]
  1351. public void SetSupportMultipleWindows(bool enabled) {
  1352. SetSupportMultipleWindows(enabled, true);
  1353. }
  1354. /// <summary>
  1355. /// Sets whether the web view should support a pop up web view triggered by user in a new tab.
  1356. ///
  1357. /// In a general web browser (such as Google Chrome or Safari), a URL with `target="_blank"` attribute is intended
  1358. /// to be opened in a new tab. However, in the context of web view, there is no way to handle new tabs without
  1359. /// proper configurations. Due to that, by default UniWebView will ignore the `target="_blank"` and try to open
  1360. /// the page in the same web view if that kind of link is pressed.
  1361. ///
  1362. /// It works for most cases, but if this is a problem to your app logic, you can change this behavior by calling
  1363. /// this method with `enabled` set to `true`. It enables the "opening in new tab" behavior in a limited way, by
  1364. /// adding the new tab web view above to the current web view, with the same size and position. When the opened new
  1365. /// tab is closed, it will be removed from the view hierarchy automatically.
  1366. ///
  1367. /// By default, only user triggered action is allowed to open a new window for security reason. That means, if you
  1368. /// are using some JavaScript like `window.open`, unless you set `allowJavaScriptOpening` to `true`, it won't work.
  1369. /// This default behavior prevents any other third party JavaScript code from opening a window arbitrarily.
  1370. ///
  1371. /// </summary>
  1372. /// <param name="enabled">
  1373. /// Whether to support multiple windows. If `true`, the `target="_blank"` link will be opened in a new web view.
  1374. /// Default is `false`.
  1375. /// </param>
  1376. /// <param name="allowJavaScriptOpening">
  1377. /// Whether to support open the new window with JavaScript by `window.open`. Setting this to `true` means any JavaScript
  1378. /// code, even from third party (in an iframe or a library on the page), can open a new window. Use it as your risk.
  1379. /// </param>
  1380. public void SetSupportMultipleWindows(bool enabled, bool allowJavaScriptOpening) {
  1381. UniWebViewInterface.SetSupportMultipleWindows(listener.Name, enabled, allowJavaScriptOpening);
  1382. }
  1383. /// <summary>
  1384. /// Sets the default font size used in the web view.
  1385. ///
  1386. /// On Android, the web view font size can be affected by the system font scale setting. Use this method to set the
  1387. /// font size in a more reasonable way, by giving the web view another default font size with the system font scale
  1388. /// considered. It can removes or reduces the effect of system font scale when displaying the web content.
  1389. ///
  1390. /// This method only works on Android. On iOS, this method does nothing since the web view will respect the font
  1391. /// size setting in your CSS styles.
  1392. /// </summary>
  1393. /// <param name="size">The target default font size set to the web view.</param>
  1394. public void SetDefaultFontSize(int size) {
  1395. #if UNITY_ANDROID && !UNITY_EDITOR
  1396. UniWebViewInterface.SetDefaultFontSize(listener.Name, size);
  1397. #endif
  1398. }
  1399. /// <summary>
  1400. /// Sets the text zoom used in the web view.
  1401. ///
  1402. /// On Android, this method call `WebSettings.setTextZoom` to the the text zoom used in the web view.
  1403. ///
  1404. /// This method only works on Android.
  1405. /// </summary>
  1406. /// <param name="textZoom">The text zoom in percent.</param>
  1407. public void SetTextZoom(int textZoom) {
  1408. #if UNITY_ANDROID && !UNITY_EDITOR
  1409. UniWebViewInterface.SetTextZoom(listener.Name, textZoom);
  1410. #endif
  1411. }
  1412. /// <summary>
  1413. /// Sets whether the drag interaction should be enabled on iOS.
  1414. ///
  1415. /// From iOS 11, the iPad web view supports the drag interaction when user long presses an image, link or text.
  1416. /// Setting this to `false` would disable the drag feather on the web view.
  1417. ///
  1418. /// This method only works on iOS. It does nothing on Android or macOS editor. Default is `true`, which means
  1419. /// drag interaction on iPad is enabled.
  1420. /// </summary>
  1421. /// <param name="enabled">
  1422. /// Whether the drag interaction should be enabled.
  1423. /// </param>
  1424. public void SetDragInteractionEnabled(bool enabled) {
  1425. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1426. UniWebViewInterface.SetDragInteractionEnabled(listener.Name, enabled);
  1427. #endif
  1428. }
  1429. /// <summary>
  1430. /// Prints current page.
  1431. ///
  1432. /// By calling this method, a native print preview panel will be brought up on iOS and Android.
  1433. /// This method does nothing on macOS editor.
  1434. /// On iOS and Android, the web view does not support JavaScript (window.print()),
  1435. /// you can only initialize a print job from Unity by this method.
  1436. /// </summary>
  1437. public void Print() {
  1438. UniWebViewInterface.Print(listener.Name);
  1439. }
  1440. /// <summary>
  1441. /// Capture the content of web view and store it to the cache path on disk with the given file name.
  1442. ///
  1443. /// When the capturing finishes, `OnCaptureSnapshotFinished` event will be raised, with an error code to indicate
  1444. /// whether the operation succeeded and an accessible disk path of the image.
  1445. ///
  1446. /// The captured image will be stored as a PNG file under the `fileName` in app's cache folder. If a file with the
  1447. /// same file name already exists, it will be overridden by the new captured image.
  1448. /// </summary>
  1449. /// <param name="fileName">
  1450. /// The file name to which the captured image is stored to, for example "screenshot.png". If empty, UniWebView will
  1451. /// pick a random UUID with "png" file extension as the file name.
  1452. /// </param>
  1453. public void CaptureSnapshot(string fileName) {
  1454. UniWebViewInterface.CaptureSnapshot(listener.Name, fileName);
  1455. }
  1456. /// <summary>
  1457. /// Scrolls the web view to a certain point.
  1458. ///
  1459. /// Use 0 for both `x` and `y` value to scroll the web view to its origin.
  1460. /// In a normal vertical web page, it is equivalent as scrolling to top.
  1461. ///
  1462. /// You can use the `animated` parameter to control whether scrolling the page with or without animation.
  1463. /// This parameter only works on iOS and Android. On macOS editor, the scrolling always happens without animation.
  1464. /// </summary>
  1465. /// <param name="x">X value of the target scrolling point.</param>
  1466. /// <param name="y">Y value of the target scrolling point.</param>
  1467. /// <param name="animated">If `true`, the scrolling happens with animation. Otherwise, it happens without
  1468. /// animation and the content is set directly.
  1469. /// </param>
  1470. public void ScrollTo(int x, int y, bool animated) {
  1471. UniWebViewInterface.ScrollTo(listener.Name, x, y, animated);
  1472. }
  1473. /// <summary>
  1474. /// Adds the URL to download inspecting list.
  1475. ///
  1476. /// If a response is received in main frame and its URL is already in the inspecting list, a download task will be
  1477. /// triggered. Check "Download Files" guide for more.
  1478. ///
  1479. /// This method only works on iOS and macOS Editor.
  1480. /// </summary>
  1481. /// <param name="urlString">The inspected URL.</param>
  1482. /// <param name="type">The download matching type used to match the URL. Default is `ExactValue`.</param>
  1483. public void AddDownloadURL(string urlString, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1484. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1485. UniWebViewInterface.AddDownloadURL(listener.Name, urlString, (int)type);
  1486. #endif
  1487. }
  1488. /// <summary>
  1489. /// Removes the URL from download inspecting list.
  1490. ///
  1491. /// If a response is received in main frame and its URL is already in the inspecting list, a download task will be
  1492. /// triggered. Check "Download Files" guide for more.
  1493. ///
  1494. /// This method only works on iOS and macOS Editor.
  1495. /// </summary>
  1496. /// <param name="urlString">The inspected URL.</param>
  1497. /// <param name="type">The download matching type used to match the URL. Default is `ExactValue`.</param>
  1498. ///
  1499. public void RemoveDownloadURL(string urlString, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1500. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1501. UniWebViewInterface.RemoveDownloadURL(listener.Name, urlString, (int)type);
  1502. #endif
  1503. }
  1504. /// <summary>
  1505. /// Adds the MIME type to download inspecting list.
  1506. ///
  1507. /// If a response is received in main frame and its MIME type is already in the inspecting list, a
  1508. /// download task will be triggered. Check "Download Files" guide for more.
  1509. ///
  1510. /// This method only works on iOS and macOS Editor.
  1511. /// </summary>
  1512. /// <param name="MIMEType">The inspected MIME type of the response.</param>
  1513. /// <param name="type">The download matching type used to match the MIME type. Default is `ExactValue`.</param>
  1514. public void AddDownloadMIMEType(string MIMEType, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1515. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1516. UniWebViewInterface.AddDownloadMIMEType(listener.Name, MIMEType, (int)type);
  1517. #endif
  1518. }
  1519. /// <summary>
  1520. /// Removes the MIME type from download inspecting list.
  1521. ///
  1522. /// If a response is received in main frame and its MIME type is already in the inspecting list, a
  1523. /// download task will be triggered. Check "Download Files" guide for more.
  1524. ///
  1525. /// This method only works on iOS and macOS Editor.
  1526. /// </summary>
  1527. /// <param name="MIMEType">The inspected MIME type of the response.</param>
  1528. /// <param name="type">The download matching type used to match the MIME type. Default is `ExactValue`.</param>
  1529. public void RemoveDownloadMIMETypes(string MIMEType, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  1530. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1531. UniWebViewInterface.RemoveDownloadMIMETypes(listener.Name, MIMEType, (int)type);
  1532. #endif
  1533. }
  1534. /// <summary>
  1535. /// Sets whether allowing users to choose the way to handle the downloaded file. Default is `true`.
  1536. ///
  1537. /// On iOS, the downloaded file will be stored in a temporary folder. Setting this to `true` will show a system
  1538. /// default share sheet and give the user a chance to send and store the file to another location (such as the
  1539. /// File app or iCloud).
  1540. ///
  1541. /// On macOS Editor, setting this to `true` will allow UniWebView to open the file in Finder.
  1542. ///
  1543. /// This method does not have any effect on Android. On Android, the file is downloaded to the Download folder.
  1544. ///
  1545. /// </summary>
  1546. /// <param name="allowed"></param>
  1547. public void SetAllowUserChooseActionAfterDownloading(bool allowed) {
  1548. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  1549. UniWebViewInterface.SetAllowUserChooseActionAfterDownloading(listener.Name, allowed);
  1550. #endif
  1551. }
  1552. /// <summary>
  1553. /// Sets whether the `OnFileDownloadStarted` and `OnFileDownloadFinished` events should be raised even for an image
  1554. /// saving action triggered by the callout (context) menu on Android.
  1555. ///
  1556. /// By default, the image saving goes through a different route and it does not trigger the `OnFileDownloadStarted`
  1557. /// and `OnFileDownloadFinished` events like other normal download tasks. Setting this with enabled with `true` if
  1558. /// you also need to get notified when user long-presses on the image and taps "Save Image" button. By default, the
  1559. /// image will be saved to the Downloads directory and you can get the path from the parameter
  1560. /// of `OnFileDownloadFinished` event.
  1561. ///
  1562. /// This only works on Android. On iOS, there is no way to get a callback or any event from the "Add to Photos"
  1563. /// button in the callout menu.
  1564. /// </summary>
  1565. /// <param name="enabled">Whether the context menu image saving action triggers the download related events.</param>
  1566. public void SetDownloadEventForContextMenuEnabled(bool enabled) {
  1567. #if UNITY_ANDROID && !UNITY_EDITOR
  1568. UniWebViewInterface.SetDownloadEventForContextMenuEnabled(listener.Name, enabled);
  1569. #endif
  1570. }
  1571. /// <summary>
  1572. /// Registers a method handler for deciding whether UniWebView should handle the request received by the web view.
  1573. ///
  1574. /// The handler is called before the web view actually starts to load the new request. You can check the request
  1575. /// properties, such as the URL, to decide whether UniWebView should continue to handle the request or not. If you
  1576. /// return `true` from the handler function, UniWebView will continue to load the request. Otherwise, UniWebView
  1577. /// will stop the loading.
  1578. /// </summary>
  1579. /// <param name="handler">
  1580. /// A handler you can implement your own logic against the input request value. You need to return a boolean value
  1581. /// to indicate whether UniWebView should continue to load the request or not as soon as possible.
  1582. /// </param>
  1583. public void RegisterShouldHandleRequest(Func<UniWebViewChannelMethodHandleRequest, bool> handler) {
  1584. object Func(object obj) => handler((UniWebViewChannelMethodHandleRequest)obj);
  1585. UniWebViewChannelMethodManager.Instance.RegisterChannelMethod(
  1586. listener.Name,
  1587. UniWebViewChannelMethod.ShouldUniWebViewHandleRequest,
  1588. Func
  1589. );
  1590. }
  1591. /// <summary>
  1592. /// Unregisters the method handler for handling request received by the web view.
  1593. ///
  1594. /// This clears the handler registered by `RegisterHandlingRequest` method.
  1595. /// </summary>
  1596. public void UnregisterShouldHandleRequest() {
  1597. UniWebViewChannelMethodManager.Instance.UnregisterChannelMethod(
  1598. listener.Name,
  1599. UniWebViewChannelMethod.ShouldUniWebViewHandleRequest
  1600. );
  1601. }
  1602. void OnDestroy() {
  1603. UniWebViewNativeListener.RemoveListener(listener.Name);
  1604. UniWebViewChannelMethodManager.Instance.UnregisterChannel(listener.Name);
  1605. UniWebViewInterface.Destroy(listener.Name);
  1606. Destroy(listener.gameObject);
  1607. }
  1608. /* //////////////////////////////////////////////////////
  1609. // Internal Listener Interface
  1610. ////////////////////////////////////////////////////// */
  1611. internal void InternalOnShowTransitionFinished(string identifier) {
  1612. Action action;
  1613. if (actions.TryGetValue(identifier, out action)) {
  1614. action();
  1615. actions.Remove(identifier);
  1616. }
  1617. }
  1618. internal void InternalOnHideTransitionFinished(string identifier) {
  1619. Action action;
  1620. if (actions.TryGetValue(identifier, out action)) {
  1621. action();
  1622. actions.Remove(identifier);
  1623. }
  1624. }
  1625. internal void InternalOnAnimateToFinished(string identifier) {
  1626. Action action;
  1627. if (actions.TryGetValue(identifier, out action)) {
  1628. action();
  1629. actions.Remove(identifier);
  1630. }
  1631. }
  1632. internal void InternalOnAddJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  1633. Action<UniWebViewNativeResultPayload> action;
  1634. var identifier = payload.identifier;
  1635. if (payloadActions.TryGetValue(identifier, out action)) {
  1636. action(payload);
  1637. payloadActions.Remove(identifier);
  1638. }
  1639. }
  1640. internal void InternalOnEvalJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  1641. Action<UniWebViewNativeResultPayload> action;
  1642. var identifier = payload.identifier;
  1643. if (payloadActions.TryGetValue(identifier, out action)) {
  1644. action(payload);
  1645. payloadActions.Remove(identifier);
  1646. }
  1647. }
  1648. internal void InternalOnPageFinished(UniWebViewNativeResultPayload payload) {
  1649. if (OnPageFinished != null) {
  1650. int code = -1;
  1651. if (int.TryParse(payload.resultCode, out code)) {
  1652. OnPageFinished(this, code, payload.data);
  1653. } else {
  1654. UniWebViewLogger.Instance.Critical("Invalid status code received: " + payload.resultCode);
  1655. }
  1656. }
  1657. }
  1658. internal void InternalOnPageStarted(string url) {
  1659. if (OnPageStarted != null) {
  1660. OnPageStarted(this, url);
  1661. }
  1662. }
  1663. internal void InternalOnPageErrorReceived(UniWebViewNativeResultPayload payload) {
  1664. if (OnPageErrorReceived != null) {
  1665. int code = -1;
  1666. if (int.TryParse(payload.resultCode, out code)) {
  1667. OnPageErrorReceived(this, code, payload.data);
  1668. } else {
  1669. UniWebViewLogger.Instance.Critical("Invalid error code received: " + payload.resultCode);
  1670. }
  1671. }
  1672. }
  1673. internal void InternalOnPageProgressChanged(float progress) {
  1674. if (OnPageProgressChanged != null) {
  1675. OnPageProgressChanged(this, progress);
  1676. }
  1677. }
  1678. internal void InternalOnMessageReceived(string result) {
  1679. if (OnMessageReceived != null) {
  1680. var message = new UniWebViewMessage(result);
  1681. OnMessageReceived(this, message);
  1682. }
  1683. }
  1684. internal void InternalOnShouldClose() {
  1685. if (OnShouldClose != null) {
  1686. var shouldClose = OnShouldClose(this);
  1687. if (shouldClose) {
  1688. Destroy(this);
  1689. }
  1690. } else {
  1691. Destroy(this);
  1692. }
  1693. }
  1694. internal void InternalOnWebContentProcessDidTerminate() {
  1695. if (OnWebContentProcessTerminated != null) {
  1696. OnWebContentProcessTerminated(this);
  1697. }
  1698. }
  1699. internal void InternalOnMultipleWindowOpened(string multiWindowId) {
  1700. if (OnMultipleWindowOpened != null) {
  1701. OnMultipleWindowOpened(this, multiWindowId);
  1702. }
  1703. }
  1704. internal void InternalOnMultipleWindowClosed(string multiWindowId) {
  1705. if (OnMultipleWindowClosed != null) {
  1706. OnMultipleWindowClosed(this, multiWindowId);
  1707. }
  1708. }
  1709. internal void InternalOnFileDownloadStarted(UniWebViewNativeResultPayload payload) {
  1710. if (OnFileDownloadStarted != null) {
  1711. OnFileDownloadStarted(this, payload.identifier, payload.data);
  1712. }
  1713. }
  1714. internal void InternalOnFileDownloadFinished(UniWebViewNativeResultPayload payload) {
  1715. if (OnFileDownloadFinished != null) {
  1716. int errorCode = int.TryParse(payload.resultCode, out errorCode) ? errorCode : -1;
  1717. OnFileDownloadFinished(this, errorCode, payload.identifier, payload.data);
  1718. }
  1719. }
  1720. internal void InternalOnCaptureSnapshotFinished(UniWebViewNativeResultPayload payload) {
  1721. if (OnCaptureSnapshotFinished != null) {
  1722. int errorCode = int.TryParse(payload.resultCode, out errorCode) ? errorCode : -1;
  1723. OnCaptureSnapshotFinished(this, errorCode, payload.data);
  1724. }
  1725. }
  1726. /// <summary>
  1727. /// Sets whether the web view should behave in immersive mode, that is,
  1728. /// hides the status bar and navigation bar with a sticky style.
  1729. ///
  1730. /// This method is only for Android. Default is enabled.
  1731. /// </summary>
  1732. /// <param name="enabled"></param>
  1733. [Obsolete("SetImmersiveModeEnabled is deprecated. Now UniWebView always respect navigation bar/status bar settings from Unity.", false)]
  1734. public void SetImmersiveModeEnabled(bool enabled) {
  1735. Debug.LogError(
  1736. "SetImmersiveModeEnabled is removed in UniWebView 4." +
  1737. "Now UniWebView always respect navigation bar/status bar settings from Unity."
  1738. );
  1739. }
  1740. /// <summary>
  1741. /// Delegate for code keycode received event.
  1742. /// </summary>
  1743. /// <param name="webView">The web view component which raises this event.</param>
  1744. /// <param name="keyCode">The key code of pressed key. See [Android API for keycode](https://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_0) to know the possible values.</param>
  1745. [Obsolete("KeyCodeReceivedDelegate is deprecated. Now UniWebView never intercepts device key code events. Check `Input.GetKeyUp` instead.", false)]
  1746. public delegate void KeyCodeReceivedDelegate(UniWebView webView, int keyCode);
  1747. /// <summary>
  1748. /// Raised when a key (like back button or volume up) on the device is pressed.
  1749. ///
  1750. /// This event only raised on Android. It is useful when you disabled the back button but still need to
  1751. /// get the back button event. On iOS, user's key action is not avaliable and this event will never be
  1752. /// raised.
  1753. /// </summary>
  1754. [Obsolete("OnKeyCodeReceived is deprecated and never called. Now UniWebView never intercepts device key code events. Check `Input.GetKeyUp` instead.", false)]
  1755. #pragma warning disable CS0067
  1756. public event KeyCodeReceivedDelegate OnKeyCodeReceived;
  1757. }