UniWebView.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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 represent a webview object in system.
  23. /// Use this class to create, load, show and interact with a 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 begins 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 successully.
  47. ///
  48. /// This method will be invoked when a valid response received from the url, regardless 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 is 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 host not found or no Internet connection will raise this event.
  66. /// </summary>
  67. public event PageErrorReceivedDelegate OnPageErrorReceived;
  68. /// <summary>
  69. /// Delegate for message received event.
  70. /// </summary>
  71. /// <param name="webView">The web view component which raises this event.</param>
  72. /// <param name="message">Message received from web view.</param>
  73. public delegate void MessageReceivedDelegate(UniWebView webView, UniWebViewMessage message);
  74. /// <summary>
  75. /// Raised when a message from web view is received.
  76. ///
  77. /// Generally, the message comes from a navigation to
  78. /// a scheme which is observed by current web view. You could use `AddUrlScheme` and
  79. /// `RemoveUrlScheme` to manipulate the scheme list.
  80. ///
  81. /// "uniwebview://" scheme is default in the list, so a clicking on link starts with "uniwebview://"
  82. /// will raise this event, if it is not removed.
  83. /// </summary>
  84. public event MessageReceivedDelegate OnMessageReceived;
  85. /// <summary>
  86. /// Delegate for should close event.
  87. /// </summary>
  88. /// <param name="webView">The web view component which raises this event.</param>
  89. /// <returns>Whether the web view should be closed and destroyed.</returns>
  90. public delegate bool ShouldCloseDelegate(UniWebView webView);
  91. /// <summary>
  92. /// Raised when the web view is about to close itself.
  93. ///
  94. /// This event is raised when the users close the web view by Back button on Android, Done button on iOS,
  95. /// or Close button on Unity Editor. It gives a chance to make final decision whether the web view should
  96. /// be closed and destroyed. You should also clean all related resources you created (such as a reference to
  97. /// the web view.)
  98. /// </summary>
  99. public event ShouldCloseDelegate OnShouldClose;
  100. /// <summary>
  101. /// Delegate for code keycode received event.
  102. /// </summary>
  103. /// <param name="webView">The web view component which raises this event.</param>
  104. /// <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>
  105. public delegate void KeyCodeReceivedDelegate(UniWebView webView, int keyCode);
  106. /// <summary>
  107. /// Raised when a key (like back button or volume up) on the device is pressed.
  108. ///
  109. /// This event only raised on Android. It is useful when you disabled the back button but still need to
  110. /// get the back button event. On iOS, user's key action is not avaliable and this event will never be
  111. /// raised.
  112. /// </summary>
  113. public event KeyCodeReceivedDelegate OnKeyCodeReceived;
  114. /// <summary>
  115. /// Delegate for orientation changed event.
  116. /// </summary>
  117. /// <param name="webView">The web view component which raises this event.</param>
  118. /// <param name="orientation">The screen orientation for current state.</param>
  119. public delegate void OrientationChangedDelegate(UniWebView webView, ScreenOrientation orientation);
  120. /// <summary>
  121. /// Raised when the screen orientation is changed. It is a good time to set the web view frame if you
  122. /// need to support multiple orientations in your game.
  123. /// </summary>
  124. public event OrientationChangedDelegate OnOrientationChanged;
  125. /// <summary>
  126. /// Delegate for content loading terminated event.
  127. /// </summary>
  128. /// <param name="webView">The web view component which raises this event.</param>
  129. public delegate void OnWebContentProcessTerminatedDelegate(UniWebView webView);
  130. /// <summary>
  131. /// Raised when on iOS, when system calls `webViewWebContentProcessDidTerminate` method.
  132. /// It is usually due to a low memory when loading the web content and leave you a blank white screen.
  133. /// You need to free as much as memory you could and then do a page reload.
  134. /// </summary>
  135. public event OnWebContentProcessTerminatedDelegate OnWebContentProcessTerminated;
  136. private string id = Guid.NewGuid().ToString();
  137. private UniWebViewNativeListener listener;
  138. private bool isPortrait;
  139. [SerializeField]
  140. #pragma warning disable 0649
  141. private string urlOnStart;
  142. [SerializeField]
  143. private bool showOnStart = false;
  144. [SerializeField]
  145. private bool fullScreen;
  146. [SerializeField]
  147. private bool useToolbar;
  148. [SerializeField]
  149. private UniWebViewToolbarPosition toolbarPosition;
  150. #pragma warning restore 0649
  151. // Action callback holders
  152. private Dictionary<String, Action> actions = new Dictionary<String, Action>();
  153. private Dictionary<String, Action<UniWebViewNativeResultPayload>> payloadActions = new Dictionary<String, Action<UniWebViewNativeResultPayload>>();
  154. [SerializeField]
  155. private Rect frame;
  156. /// <summary>
  157. /// Get or Set the frame of current web view. The value is based on current `Screen.width` and `Screen.height`.
  158. /// The first two values of `Rect` is `x` and `y` position and the followed two `width` and `height`.
  159. /// </summary>
  160. public Rect Frame {
  161. get { return frame; }
  162. set {
  163. frame = value;
  164. UpdateFrame();
  165. }
  166. }
  167. [SerializeField]
  168. private RectTransform referenceRectTransform;
  169. /// <summary>
  170. /// A reference rect transform which the web view should change its position and size to.
  171. /// Set it to a Unity UI element (which contains a `RectTransform`) under a canvas to determine
  172. /// the web view frame by a certain UI element.
  173. ///
  174. /// By using this, you could get benefit from [Multiple Resolutions UI](https://docs.unity3d.com/Manual/HOWTO-UIMultiResolution.html).
  175. ///
  176. /// </summary>
  177. public RectTransform ReferenceRectTransform {
  178. get {
  179. return referenceRectTransform;
  180. }
  181. set {
  182. referenceRectTransform = value;
  183. UpdateFrame();
  184. }
  185. }
  186. private bool started;
  187. /// <summary>
  188. /// The url of current loaded web page.
  189. /// </summary>
  190. public string Url {
  191. get { return UniWebViewInterface.GetUrl(listener.Name); }
  192. }
  193. /// <summary>
  194. /// Update and set current frame of web view to match the setting.
  195. ///
  196. /// This is useful if the `referenceRectTransform` is changed and you need to sync the frame change
  197. /// to the web view. This method follows the frame determining rules.
  198. /// </summary>
  199. public void UpdateFrame() {
  200. Rect rect = NextFrameRect();
  201. UniWebViewInterface.SetFrame(listener.Name, (int)rect.x, (int)rect.y, (int)rect.width, (int)rect.height);
  202. }
  203. Rect NextFrameRect() {
  204. if (referenceRectTransform == null) {
  205. UniWebViewLogger.Instance.Info("Using Frame setting to determine web view frame.");
  206. return frame;
  207. } else {
  208. UniWebViewLogger.Instance.Info("Using reference RectTransform to determine web view frame.");
  209. var worldCorners = new Vector3[4];
  210. referenceRectTransform.GetWorldCorners(worldCorners);
  211. var bottomLeft = worldCorners[0];
  212. var topLeft = worldCorners[1];
  213. var topRight = worldCorners[2];
  214. var bottomRight = worldCorners[3];
  215. var canvas = referenceRectTransform.GetComponentInParent<Canvas>();
  216. if (canvas == null) {
  217. return frame;
  218. }
  219. switch (canvas.renderMode) {
  220. case RenderMode.ScreenSpaceOverlay:
  221. break;
  222. case RenderMode.ScreenSpaceCamera:
  223. case RenderMode.WorldSpace:
  224. var camera = canvas.worldCamera;
  225. if (camera == null) {
  226. UniWebViewLogger.Instance.Critical(@"You need a render camera
  227. or event camera to use RectTransform to determine correct
  228. frame for UniWebView.");
  229. UniWebViewLogger.Instance.Info("No camera found. Fall back to ScreenSpaceOverlay mode.");
  230. } else {
  231. bottomLeft = camera.WorldToScreenPoint(bottomLeft);
  232. topLeft = camera.WorldToScreenPoint(topLeft);
  233. topRight = camera.WorldToScreenPoint(topRight);
  234. bottomRight = camera.WorldToScreenPoint(bottomRight);
  235. }
  236. break;
  237. }
  238. float x = topLeft.x;
  239. float y = Screen.height - topLeft.y;
  240. float width = bottomRight.x - topLeft.x;
  241. float height = topLeft.y - bottomRight.y;
  242. return new Rect(x, y, width, height);
  243. }
  244. }
  245. void Awake() {
  246. var listenerObject = new GameObject(id);
  247. listener = listenerObject.AddComponent<UniWebViewNativeListener>();
  248. listenerObject.transform.parent = transform;
  249. listener.webView = this;
  250. UniWebViewNativeListener.AddListener(listener);
  251. Rect rect;
  252. if (fullScreen) {
  253. rect = new Rect(0, 0, Screen.width, Screen.height);
  254. } else {
  255. rect = NextFrameRect();
  256. }
  257. UniWebViewInterface.Init(listener.Name, (int)rect.x, (int)rect. y, (int)rect.width, (int)rect.height);
  258. isPortrait = Screen.height >= Screen.width;
  259. }
  260. void Start() {
  261. if (showOnStart) {
  262. Show();
  263. }
  264. if (!string.IsNullOrEmpty(urlOnStart)) {
  265. Load(urlOnStart);
  266. }
  267. started = true;
  268. if (referenceRectTransform != null) {
  269. UpdateFrame();
  270. }
  271. }
  272. void Update() {
  273. var newIsPortrait = Screen.height >= Screen.width;
  274. if (isPortrait != newIsPortrait) {
  275. isPortrait = newIsPortrait;
  276. if (OnOrientationChanged != null) {
  277. OnOrientationChanged(this, isPortrait ? ScreenOrientation.Portrait : ScreenOrientation.LandscapeLeft);
  278. }
  279. if (referenceRectTransform != null) {
  280. UpdateFrame();
  281. }
  282. }
  283. }
  284. void OnEnable() {
  285. if (started) {
  286. #if UNITY_ANDROID && !UNITY_EDITOR
  287. UniWebViewInterface.ShowWebViewDialog(listener.Name, true);
  288. #endif
  289. Show();
  290. }
  291. }
  292. void OnDisable() {
  293. if (started) {
  294. Hide();
  295. #if UNITY_ANDROID && !UNITY_EDITOR
  296. UniWebViewInterface.ShowWebViewDialog(listener.Name, false);
  297. #endif
  298. }
  299. }
  300. /// <summary>
  301. /// Load a url in current web view.
  302. /// </summary>
  303. /// <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>
  304. /// <param name="skipEncoding">
  305. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  306. /// loading it. Otherwise, your original url string will be used as the url if it is valid. Default is `false`.
  307. /// </param>
  308. /// <param name="readAccessURL">
  309. /// The URL to allow read access to. This parameter is only used when loading from the filesystem in iOS, and passed
  310. /// to `loadFileURL:allowingReadAccessToURL:` method of WebKit. By default, the parent folder of the `url` parameter will be read accessible.
  311. /// </param>
  312. public void Load(string url, bool skipEncoding = false, string readAccessURL = null) {
  313. UniWebViewInterface.Load(listener.Name, url, skipEncoding, readAccessURL);
  314. }
  315. /// <summary>
  316. /// Load an HTML string in current web view.
  317. /// </summary>
  318. /// <param name="htmlString">The HTML string to use as the contents of the webpage.</param>
  319. /// <param name="baseUrl">The url to use as the page's base url.</param>
  320. /// <param name="skipEncoding">
  321. /// Whether UniWebView should skip encoding the baseUrl or not. If set to `false`, UniWebView will try to encode the baseUrl parameter before
  322. /// using it. Otherwise, your original url string will be used as the baseUrl if it is valid. Default is `false`.
  323. /// </param>
  324. public void LoadHTMLString(string htmlString, string baseUrl, bool skipEncoding = false) {
  325. UniWebViewInterface.LoadHTMLString(listener.Name, htmlString, baseUrl, skipEncoding);
  326. }
  327. /// <summary>
  328. /// Reloads the current page.
  329. /// </summary>
  330. public void Reload() {
  331. UniWebViewInterface.Reload(listener.Name);
  332. }
  333. /// <summary>
  334. /// Stops loading all resources on the current page.
  335. /// </summary>
  336. public void Stop() {
  337. UniWebViewInterface.Stop(listener.Name);
  338. }
  339. /// <summary>
  340. /// Gets whether there is a back page in the back-forward list that can be navigated to.
  341. /// </summary>
  342. public bool CanGoBack {
  343. get {
  344. return UniWebViewInterface.CanGoBack(listener.name);
  345. }
  346. }
  347. /// <summary>
  348. /// Gets whether there is a forward page in the back-forward list that can be navigated to.
  349. /// </summary>
  350. public bool CanGoForward {
  351. get {
  352. return UniWebViewInterface.CanGoForward(listener.name);
  353. }
  354. }
  355. /// <summary>
  356. /// Navigates to the back item in the back-forward list.
  357. /// </summary>
  358. public void GoBack() {
  359. UniWebViewInterface.GoBack(listener.Name);
  360. }
  361. /// <summary>
  362. /// Navigates to the forward item in the back-forward list.
  363. /// </summary>
  364. public void GoForward() {
  365. UniWebViewInterface.GoForward(listener.Name);
  366. }
  367. /// <summary>
  368. /// Sets whether the link clicking in the web view should open the page in an external browser.
  369. /// </summary>
  370. /// <param name="flag">The flag indicates whether a link should be opened externally.</param>
  371. public void SetOpenLinksInExternalBrowser(bool flag) {
  372. UniWebViewInterface.SetOpenLinksInExternalBrowser(listener.Name, flag);
  373. }
  374. /// <summary>
  375. /// Sets the web view visible on screen.
  376. /// </summary>
  377. /// <param name="fade">Whether show with a fade in animation. Default is `false`.</param>
  378. /// <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>
  379. /// <param name="duration">Duration of showing animation. Default is `0.4f`.</param>
  380. /// <param name="completionHandler">Completion handler which will be called when showing finishes. Default is `null`.</param>
  381. /// <returns>A bool value indicates whether the showing operation started.</returns>
  382. public bool Show(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  383. float duration = 0.4f, Action completionHandler = null)
  384. {
  385. var identifier = Guid.NewGuid().ToString();
  386. var showStarted = UniWebViewInterface.Show(listener.Name, fade, (int)edge, duration, identifier);
  387. if (showStarted && completionHandler != null) {
  388. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  389. if (hasAnimation) {
  390. actions.Add(identifier, completionHandler);
  391. } else {
  392. completionHandler();
  393. }
  394. }
  395. if (showStarted && useToolbar) {
  396. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  397. SetShowToolbar(true, false, top, fullScreen);
  398. }
  399. return showStarted;
  400. }
  401. /// <summary>
  402. /// Sets the web view invisible from screen.
  403. /// </summary>
  404. /// <param name="fade">Whether hide with a fade in animation. Default is `false`.</param>
  405. /// <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>
  406. /// <param name="duration">Duration of hiding animation. Default is `0.4f`.</param>
  407. /// <param name="completionHandler">Completion handler which will be called when hiding finishes. Default is `null`.</param>
  408. /// <returns>A bool value indicates whether the hiding operation started.</returns>
  409. public bool Hide(bool fade = false, UniWebViewTransitionEdge edge = UniWebViewTransitionEdge.None,
  410. float duration = 0.4f, Action completionHandler = null)
  411. {
  412. var identifier = Guid.NewGuid().ToString();
  413. var hideStarted = UniWebViewInterface.Hide(listener.Name, fade, (int)edge, duration, identifier);
  414. if (hideStarted && completionHandler != null) {
  415. var hasAnimation = (fade || edge != UniWebViewTransitionEdge.None);
  416. if (hasAnimation) {
  417. actions.Add(identifier, completionHandler);
  418. } else {
  419. completionHandler();
  420. }
  421. }
  422. if (hideStarted && useToolbar) {
  423. var top = (toolbarPosition == UniWebViewToolbarPosition.Top);
  424. SetShowToolbar(false, false, top, fullScreen);
  425. }
  426. return hideStarted;
  427. }
  428. /// <summary>
  429. /// Animates the web view from current position and size to another position and size.
  430. /// </summary>
  431. /// <param name="frame">The new `Frame` which the web view should be.</param>
  432. /// <param name="duration">Duration of the animation.</param>
  433. /// <param name="delay">Delay before the animation begins. Default is `0.0f`, which means the animation will start immediately.</param>
  434. /// <param name="completionHandler">Completion handler which will be called when animation finishes. Default is `null`.</param>
  435. /// <returns></returns>
  436. public bool AnimateTo(Rect frame, float duration, float delay = 0.0f, Action completionHandler = null) {
  437. var identifier = Guid.NewGuid().ToString();
  438. var animationStarted = UniWebViewInterface.AnimateTo(listener.Name,
  439. (int)frame.x, (int)frame.y, (int)frame.width, (int)frame.height, duration, delay, identifier);
  440. if (animationStarted) {
  441. this.frame = frame;
  442. if (completionHandler != null) {
  443. actions.Add(identifier, completionHandler);
  444. }
  445. }
  446. return animationStarted;
  447. }
  448. /// <summary>
  449. /// Adds a JavaScript to current page.
  450. /// </summary>
  451. /// <param name="jsString">The JavaScript code to add. It should be a valid JavaScript statement string.</param>
  452. /// <param name="completionHandler">Called when adding JavaScript operation finishes. Default is `null`.</param>
  453. public void AddJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  454. var identifier = Guid.NewGuid().ToString();
  455. UniWebViewInterface.AddJavaScript(listener.Name, jsString, identifier);
  456. if (completionHandler != null) {
  457. payloadActions.Add(identifier, completionHandler);
  458. }
  459. }
  460. /// <summary>
  461. /// Evaluates a JavaScript string on current page.
  462. /// </summary>
  463. /// <param name="jsString">The JavaScript string to evaluate.</param>
  464. /// <param name="completionHandler">Called when evaluating JavaScript operation finishes. Default is `null`.</param>
  465. public void EvaluateJavaScript(string jsString, Action<UniWebViewNativeResultPayload> completionHandler = null) {
  466. var identifier = Guid.NewGuid().ToString();
  467. UniWebViewInterface.EvaluateJavaScript(listener.Name, jsString, identifier);
  468. if (completionHandler != null) {
  469. payloadActions.Add(identifier, completionHandler);
  470. }
  471. }
  472. /// <summary>
  473. /// Adds a url scheme to UniWebView message system interpreter.
  474. /// All following url navigation to this scheme will be sent as a message to UniWebView instead.
  475. /// </summary>
  476. /// <param name="scheme">The url scheme to add. It should not contain "://" part. You could even add "http" and/or "https" to prevent all resource loading on the page. "uniwebview" is added by default. Nothing will happen if you try to add a dulplicated scheme.</param>
  477. public void AddUrlScheme(string scheme) {
  478. if (scheme == null) {
  479. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  480. return;
  481. }
  482. if (scheme.Contains("://")) {
  483. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  484. return;
  485. }
  486. UniWebViewInterface.AddUrlScheme(listener.Name, scheme);
  487. }
  488. /// <summary>
  489. /// Removes a url scheme from UniWebView message system interpreter.
  490. /// </summary>
  491. /// <param name="scheme">The url scheme to remove. Nothing will happen if the scheme is not in the message system.</param>
  492. public void RemoveUrlScheme(string scheme) {
  493. if (scheme == null) {
  494. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  495. return;
  496. }
  497. if (scheme.Contains("://")) {
  498. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  499. return;
  500. }
  501. UniWebViewInterface.RemoveUrlScheme(listener.Name, scheme);
  502. }
  503. /// <summary>
  504. /// Adds a domain to the SSL checking white list.
  505. /// If you are trying to access a web site with untrusted or expired certification,
  506. /// the web view will prevent its loading. If you could confirm that this site is trusted,
  507. /// you can add the domain as an SSL exception, so you could visit it.
  508. /// </summary>
  509. /// <param name="domain">The domain to add. It should not contain any scheme or path part in url.</param>
  510. public void AddSslExceptionDomain(string domain) {
  511. if (domain == null) {
  512. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  513. return;
  514. }
  515. if (domain.Contains("://")) {
  516. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  517. return;
  518. }
  519. UniWebViewInterface.AddSslExceptionDomain(listener.Name, domain);
  520. }
  521. /// <summary>
  522. /// Removes a domain from the SSL checking white list.
  523. /// </summary>
  524. /// <param name="domain">The domain to remove. It should not contain any scheme or path part in url.</param>
  525. public void RemoveSslExceptionDomain(string domain) {
  526. if (domain == null) {
  527. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  528. return;
  529. }
  530. if (domain.Contains("://")) {
  531. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  532. return;
  533. }
  534. UniWebViewInterface.RemoveSslExceptionDomain(listener.Name, domain);
  535. }
  536. /// <summary>
  537. /// Sets a customized header field for web view requests.
  538. ///
  539. /// The header field will be used for all subsequence reqeust.
  540. /// Pass `null` as value to unset a header field.
  541. ///
  542. /// Some reserved headers like user agent are not be able to override by setting here,
  543. /// use the `SetUserAgent` method for them instead.
  544. /// </summary>
  545. /// <param name="key">The key of customized header field.</param>
  546. /// <param name="value">The value of customized header field. `null` if you want to unset the field.</param>
  547. public void SetHeaderField(string key, string value) {
  548. if (key == null) {
  549. UniWebViewLogger.Instance.Critical("Header key should not be null.");
  550. return;
  551. }
  552. UniWebViewInterface.SetHeaderField(listener.Name, key, value);
  553. }
  554. /// <summary>
  555. /// Sets the user agent used in the web view.
  556. /// If the string is null or empty, the system default value will be used.
  557. /// </summary>
  558. /// <param name="agent">The new user agent string to use.</param>
  559. public void SetUserAgent(string agent) {
  560. UniWebViewInterface.SetUserAgent(listener.Name, agent);
  561. }
  562. /// <summary>
  563. /// Gets the user agent string currently used in web view.
  564. /// If a customized user agent is not set, the default user agent in current platform will be returned.
  565. /// </summary>
  566. /// <returns>The user agent string in use.</returns>
  567. public string GetUserAgent() {
  568. return UniWebViewInterface.GetUserAgent(listener.Name);
  569. }
  570. /// <summary>
  571. /// Set allow auto play for current web view. By default,
  572. /// users need to touch the play button to start playing a media resource.
  573. /// By setting this to `true`, you could start the playing automatically through
  574. /// corresponding media tag attributes.
  575. /// </summary>
  576. /// <param name="flag">A flag indicates whether autoplaying of media is allowed or not.</param>
  577. public static void SetAllowAutoPlay(bool flag) {
  578. UniWebViewInterface.SetAllowAutoPlay(flag);
  579. }
  580. /// <summary>
  581. /// Set allow inline play for current web view. By default, on iOS, the video
  582. /// can only be played in a new full screen view.
  583. /// By setting this to `true`, you could play a video inline the page, instead of opening
  584. /// a new full screen window.
  585. ///
  586. /// This only works for iOS and macOS Editor.
  587. /// On Android, you could play videos inline by default and calling this method does nothing.
  588. /// </summary>
  589. /// <param name="flag">A flag indicates whether inline playing of media is allowed or not.</param>
  590. public static void SetAllowInlinePlay(bool flag) {
  591. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN
  592. UniWebViewInterface.SetAllowInlinePlay(flag);
  593. #endif
  594. }
  595. /// <summary>
  596. /// Sets whether JavaScript should be enabled in current web view. Default is enabled.
  597. /// </summary>
  598. /// <param name="enabled">Whether JavaScript should be enabled.</param>
  599. public static void SetJavaScriptEnabled(bool enabled) {
  600. UniWebViewInterface.SetJavaScriptEnabled(enabled);
  601. }
  602. /// <summary>
  603. /// Sets whether JavaScript can open windows without user interaction.
  604. ///
  605. /// By setting this to `true`, an automatically JavaScript navigation will be allowed in the web view.
  606. /// </summary>
  607. /// <param name="flag">Whether JavaScript could open window automatically.</param>
  608. public static void SetAllowJavaScriptOpenWindow(bool flag) {
  609. UniWebViewInterface.SetAllowJavaScriptOpenWindow(flag);
  610. }
  611. /// <summary>
  612. /// Clean web view cache. This removes cached local data of web view.
  613. ///
  614. /// If you need to clear all cookies, use `ClearCookies` instead.
  615. /// </summary>
  616. public void CleanCache() {
  617. UniWebViewInterface.CleanCache(listener.Name);
  618. }
  619. /// <summary>
  620. /// Clears all cookies from web view.
  621. ///
  622. /// This will clear cookies from all domains in the web view and previous.
  623. /// If you only need to remove cookies from a certain domain, use `SetCookie` instead.
  624. /// </summary>
  625. public static void ClearCookies() {
  626. UniWebViewInterface.ClearCookies();
  627. }
  628. /// <summary>
  629. /// Sets a cookie for a certain url.
  630. /// </summary>
  631. /// <param name="url">The url to which cookie will be set.</param>
  632. /// <param name="cookie">The cookie string to set.</param>
  633. /// <param name="skipEncoding">
  634. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  635. /// using it. Otherwise, your original url string will be used to set the cookie if it is valid. Default is `false`.
  636. /// </param>
  637. public static void SetCookie(string url, string cookie, bool skipEncoding = false) {
  638. UniWebViewInterface.SetCookie(url, cookie, skipEncoding);
  639. }
  640. /// <summary>
  641. /// Gets the cookie value under a url and key.
  642. /// </summary>
  643. /// <param name="url">The url (domain) where the target cookie is.</param>
  644. /// <param name="key">The key for target cookie value.</param>
  645. /// <param name="skipEncoding">
  646. /// Whether UniWebView should skip encoding the url or not. If set to `false`, UniWebView will try to encode the url parameter before
  647. /// using it. Otherwise, your original url string will be used to get the cookie if it is valid. Default is `false`.
  648. /// </param>
  649. /// <returns>Value of the target cookie under url.</returns>
  650. public static string GetCookie(string url, string key, bool skipEncoding = false) {
  651. return UniWebViewInterface.GetCookie(url, key, skipEncoding);
  652. }
  653. /// <summary>
  654. /// Clears any saved credentials for HTTP authentication for both Basic and Digest.
  655. ///
  656. /// On both iOS and Android, the user input credentials will be stored permanently across session.
  657. /// It could prevent your users to input username and password again until they changed. If you need the
  658. /// credentials only living in a shorter lifetime, call this method at proper timing.
  659. ///
  660. /// On iOS, it will clear the credentials immediately and completely from both disk and network cache.
  661. /// On Android, it only clears from disk database, the authentication might be still cached in the network stack
  662. /// and will not be removed until next session (app restarting).
  663. ///
  664. /// The client logout mechanism should be implemented by the Web site designer (such as server sending a HTTP
  665. /// 401 for invalidating credentials).
  666. ///
  667. /// </summary>
  668. /// <param name="host">The host to which the credentials apply. It should not contain any thing like scheme or path part.</param>
  669. /// <param name="realm">The realm to which the credentials apply.</param>
  670. public static void ClearHttpAuthUsernamePassword(string host, string realm) {
  671. UniWebViewInterface.ClearHttpAuthUsernamePassword(host, realm);
  672. }
  673. private Color backgroundColor = Color.white;
  674. /// <summary>
  675. /// Gets or sets the background color of web view. The default value is `Color.white`.
  676. /// </summary>
  677. public Color BackgroundColor {
  678. get {
  679. return backgroundColor;
  680. }
  681. set {
  682. backgroundColor = value;
  683. UniWebViewInterface.SetBackgroundColor(listener.Name, value.r, value.g, value.b, value.a);
  684. }
  685. }
  686. /// <summary>
  687. /// Gets or sets the alpha value of the whole web view.
  688. ///
  689. /// You could make the game scene behind web view visible to make the web view transparent.
  690. ///
  691. /// Default is `1.0f`, which means totally opaque. Set it to `0.0f` will make the web view totally transparent.
  692. /// </summary>
  693. public float Alpha {
  694. get {
  695. return UniWebViewInterface.GetWebViewAlpha(listener.Name);
  696. }
  697. set {
  698. UniWebViewInterface.SetWebViewAlpha(listener.Name, value);
  699. }
  700. }
  701. /// <summary>
  702. /// Sets whether to show a loading indicator while the loading is in progress.
  703. /// </summary>
  704. /// <param name="flag">Whether an indicator should show.</param>
  705. public void SetShowSpinnerWhileLoading(bool flag) {
  706. UniWebViewInterface.SetShowSpinnerWhileLoading(listener.Name, flag);
  707. }
  708. /// <summary>
  709. /// Sets the text displayed in the loading indicator, if `SetShowSpinnerWhileLoading` is set to `true`.
  710. /// </summary>
  711. /// <param name="text">The text to display while loading indicator visible. Default is "Loading..."</param>
  712. public void SetSpinnerText(string text) {
  713. UniWebViewInterface.SetSpinnerText(listener.Name, text);
  714. }
  715. /// <summary>
  716. /// Sets whether the horizontal scroll bar should show when the web content beyonds web view bounds.
  717. ///
  718. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  719. /// </summary>
  720. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  721. public void SetHorizontalScrollBarEnabled(bool enabled) {
  722. UniWebViewInterface.SetHorizontalScrollBarEnabled(listener.Name, enabled);
  723. }
  724. /// <summary>
  725. /// Sets whether the vertical scroll bar should show when the web content beyonds web view bounds.
  726. ///
  727. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  728. /// </summary>
  729. /// <param name="enabled">Whether enable the scroll bar or not.</param>
  730. public void SetVerticalScrollBarEnabled(bool enabled) {
  731. UniWebViewInterface.SetVerticalScrollBarEnabled(listener.Name, enabled);
  732. }
  733. /// <summary>
  734. /// Sets whether the web view should show with a bounces effect when scrolling to page edge.
  735. ///
  736. /// This only works on mobile platforms. It will do nothing on macOS Editor.
  737. /// </summary>
  738. /// <param name="enabled">Whether the bounces effect should be applied or not.</param>
  739. public void SetBouncesEnabled(bool enabled) {
  740. UniWebViewInterface.SetBouncesEnabled(listener.Name, enabled);
  741. }
  742. /// <summary>
  743. /// Sets whether the web view supports zoom guesture to change content size.
  744. /// Default is `false`, which means the zoom guesture is not supported.
  745. /// </summary>
  746. /// <param name="enabled">Whether the zoom guesture is allowed or not.</param>
  747. public void SetZoomEnabled(bool enabled) {
  748. UniWebViewInterface.SetZoomEnabled(listener.Name, enabled);
  749. }
  750. /// <summary>
  751. /// Adds a trusted domain to white list and allow permission requests from the domain.
  752. ///
  753. /// You only need this on Android devices with system before 6.0 when a site needs the location or camera
  754. /// permission. It will allow the permission gets approved so you could access the corresponding devices.
  755. /// From Android 6.0, the permission requests method is changed and this is not needed anymore.
  756. /// </summary>
  757. /// <param name="domain">The domain to add to the white list.</param>
  758. public void AddPermissionTrustDomain(string domain) {
  759. #if UNITY_ANDROID && !UNITY_EDITOR
  760. UniWebViewInterface.AddPermissionTrustDomain(listener.Name, domain);
  761. #endif
  762. }
  763. /// <summary>
  764. /// Removes a trusted domain from white list.
  765. /// </summary>
  766. /// <param name="domain">The domain to remove from white list.</param>
  767. public void RemovePermissionTrustDomain(string domain) {
  768. #if UNITY_ANDROID && !UNITY_EDITOR
  769. UniWebViewInterface.RemovePermissionTrustDomain(listener.Name, domain);
  770. #endif
  771. }
  772. /// <summary>
  773. /// Sets whether the device back button should be enabled to execute "go back" or "closing" operation.
  774. ///
  775. /// On Android, the device back button in navigation bar will navigate users to a back page. If there is
  776. /// no any back page avaliable, the back button clicking will try to raise a `OnShouldClose` event and try
  777. /// to close the web view if `true` is return from the event. If the `OnShouldClose` is not listened,
  778. /// the web view will be closed and the UniWebView component will be destroyed to release using resource.
  779. ///
  780. /// Listen to `OnKeyCodeReceived` if you need to disable the back button, but still want to get the back
  781. /// button key pressing event.
  782. ///
  783. /// Default is enabled.
  784. /// </summary>
  785. /// <param name="enabled">Whether the back button should perform go back or closing operation to web view.</param>
  786. public void SetBackButtonEnabled(bool enabled) {
  787. #if UNITY_ANDROID && !UNITY_EDITOR
  788. UniWebViewInterface.SetBackButtonEnabled(listener.Name, enabled);
  789. #endif
  790. }
  791. /// <summary>
  792. /// Sets whether the web view should enable support for the "viewport" HTML meta tag or should use a wide viewport.
  793. /// </summary>
  794. /// <param name="flag">Whether to enable support for the viewport meta tag.</param>
  795. public void SetUseWideViewPort(bool flag) {
  796. #if UNITY_ANDROID && !UNITY_EDITOR
  797. UniWebViewInterface.SetUseWideViewPort(listener.Name, flag);
  798. #endif
  799. }
  800. /// <summary>
  801. /// Sets whether the web view loads pages in overview mode, that is, zooms out the content to fit on screen by width.
  802. ///
  803. /// This method is only for Android. Default is disabled.
  804. /// </summary>
  805. /// <param name="flag"></param>
  806. public void SetLoadWithOverviewMode(bool flag) {
  807. #if UNITY_ANDROID && !UNITY_EDITOR
  808. UniWebViewInterface.SetLoadWithOverviewMode(listener.Name, flag);
  809. #endif
  810. }
  811. /// <summary>
  812. /// Sets whether the web view should behave in immersive mode, that is,
  813. /// hides the status bar and navigation bar with a sticky style.
  814. ///
  815. /// This method is only for Android. Default is enabled.
  816. /// </summary>
  817. /// <param name="enabled"></param>
  818. public void SetImmersiveModeEnabled(bool enabled) {
  819. #if UNITY_ANDROID && !UNITY_EDITOR
  820. UniWebViewInterface.SetImmersiveModeEnabled(listener.Name, enabled);
  821. #endif
  822. }
  823. /// <summary>
  824. /// Sets whether to show a toolbar which contains navigation buttons and Done button.
  825. ///
  826. /// You could choose to show or hide the tool bar. By configuring the `animated` and `onTop`
  827. /// parameters, you can control the animating and position of the toolbar. If the toolbar is
  828. /// overlapping with some part of your web view, pass `adjustInset` with `true` to have the
  829. /// web view reloacating itself to avoid the overlap.
  830. ///
  831. /// This method is only for iOS. The toolbar is hidden by default.
  832. /// </summary>
  833. /// <param name="show">Whether the toolbar should show or hide.</param>
  834. /// <param name="animated">Whether the toolbar state changing should be with animation. Default is `false`.</param>
  835. /// <param name="onTop">Whether the toolbar should snap to top of screen or to bottom of screen. Default is `true`</param>
  836. /// <param name="adjustInset">Whether the toolbar transition should also afjust web view position and size if overlapped. Default is `false`</param>
  837. public void SetShowToolbar(bool show, bool animated = false, bool onTop = true, bool adjustInset = false) {
  838. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN
  839. UniWebViewInterface.SetShowToolbar(listener.Name, show, animated, onTop, adjustInset);
  840. #endif
  841. }
  842. /// <summary>
  843. /// Sets the done button text in toolbar.
  844. ///
  845. /// By default, UniWebView will show a "Done" button at bottom-right corner in the
  846. /// toolbar. You could change its title by passing a text.
  847. ///
  848. /// This method is only for iOS, since there is no toolbar on Android.
  849. /// </summary>
  850. /// <param name="text">The text needed to be set as done button title.</param>
  851. public void SetToolbarDoneButtonText(string text) {
  852. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN
  853. UniWebViewInterface.SetToolbarDoneButtonText(listener.Name, text);
  854. #endif
  855. }
  856. /// <summary>
  857. /// Enables debugging of web contents. You could inspect of the content of a
  858. /// web view by using a browser development tool of Chrome for Android or Safari for macOS.
  859. ///
  860. /// This method is only for Android and macOS Editor. On iOS, you do not need additional step.
  861. /// You could open Safari's developer tools to debug a web view on iOS.
  862. /// </summary>
  863. /// <param name="enabled">Whether the content debugging should be enabled.</param>
  864. public static void SetWebContentsDebuggingEnabled(bool enabled) {
  865. UniWebViewInterface.SetWebContentsDebuggingEnabled(enabled);
  866. }
  867. /// <summary>
  868. /// Enables user resizing for web view window. By default, you can only set the window size
  869. /// by setting its frame on mac Editor. By enabling user resizing, you would be able to resize
  870. /// the window by dragging its border as a normal macOS window.
  871. ///
  872. /// This method only works for macOS for debugging purpose. It does nothing on iOS and Android.
  873. /// </summary>
  874. /// <param name="enabled">Whether the window could be able to be resized by cursor.</param>
  875. public void SetWindowUserResizeEnabled(bool enabled) {
  876. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN
  877. UniWebViewInterface.SetWindowUserResizeEnabled(listener.name, enabled);
  878. #endif
  879. }
  880. /// <summary>
  881. /// Gets the HTML content from current page by accessing its outerHTML with JavaScript.
  882. /// </summary>
  883. /// <param name="handler">Called after the JavaScript executed. The parameter string is the content read from page.</param>
  884. public void GetHTMLContent(Action<string> handler) {
  885. EvaluateJavaScript("document.documentElement.outerHTML", payload => {
  886. if (handler != null) {
  887. handler(payload.data);
  888. }
  889. });
  890. }
  891. /// <summary>
  892. /// Sets whether file access from file URLs is allowed.
  893. ///
  894. /// By setting with `true`, access to file URLs inside the web view will be enabled and you could access sub-resources or
  895. /// make cross origin requests from local HTML files. This method only works on iOS. The file accessing from file URLs on
  896. /// Android is available by default.
  897. /// </summary>
  898. /// <param name="flag">Whether the file access from file URLs is allowed or not.</param>
  899. public void SetAllowFileAccessFromFileURLs(bool flag) {
  900. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN
  901. UniWebViewInterface.SetAllowFileAccessFromFileURLs(listener.name, flag);
  902. #endif
  903. }
  904. /// <summary>
  905. /// Sets whether a prompt alert should be displayed for collection username and password when the web view receives an
  906. /// HTTP authentication challenge (HTTP Basic or HTTP Digest) from server.
  907. ///
  908. /// By setting with `false`, no prompt will be shown and the user cannot login with input credentials. In this case,
  909. /// you can only access this page by providing username and password through the URL like: "http://username:password@example.com".
  910. /// If the username and password does not match, normally an error with 401 as status code would be returned (this behavior depends
  911. /// on the server implementation). If set with `true`, a prompt will be shown when there is no credentials provided or it is not
  912. /// correct in the URL.
  913. ///
  914. /// Default is `true`.
  915. /// </summary>
  916. /// <param name="flag">Whether a prompt alert should be shown for HTTP authentication challenge or not.</param>
  917. public void SetAllowHTTPAuthPopUpWindow(bool flag) {
  918. UniWebViewInterface.SetAllowHTTPAuthPopUpWindow(listener.name, flag);
  919. }
  920. /// <summary>
  921. /// Sets whether a callout (context) menu should be displayed when user long tapping on certain web view content.
  922. ///
  923. /// When enabled, when user long presses an image or link in the web page, a context menu would be show up to ask
  924. /// user's action. On iOS, it is a action sheet to ask whether opening the target link or saving the image. On
  925. /// Android it is a pop up dialog to ask whether saving the image to local disk. On iOS, the preview page triggered
  926. /// by force touch on iOS is also considered as a callout menu.
  927. ///
  928. /// Default is `true`, means that the callout menu will be displayed. Call this method with `false` to disable
  929. /// it on the web view.
  930. /// </summary>
  931. /// <param name="enabled">
  932. /// Whether a callout menu should be displayed when user long pressing or force touching a certain web page element.
  933. /// </param>
  934. public void SetCalloutEnabled(bool enabled) {
  935. UniWebViewInterface.SetCalloutEnabled(listener.name, enabled);
  936. }
  937. /// <summary>
  938. /// Sets whether the drag interaction should be enabled on iOS.
  939. ///
  940. /// From iOS 11, the iPad web view supports the drag interaction when user long presses an image, link or text.
  941. /// Setting this to `false` would disable the drag feather on the web view.
  942. ///
  943. /// This method only works on iOS. It does nothing on Android or macOS editor. Default is `true`, which means
  944. /// drag interaction on iPad is enabled.
  945. /// </summary>
  946. /// <param name="enabled">
  947. /// Whether the drag interaction should be enabled.
  948. /// </param>
  949. public void SetDragInteractionEnabled(bool enabled) {
  950. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN
  951. UniWebViewInterface.SetDragInteractionEnabled(listener.name, enabled);
  952. #endif
  953. }
  954. /// <summary>
  955. /// Prints current page.
  956. ///
  957. /// By calling this method, a native print preview panel will be brought up on iOS and Android.
  958. /// This method does nothing on macOS editor.
  959. /// On iOS and Android, the web view does not support JavaScript (window.print()),
  960. /// you can only initialize a print job from Unity by this method.
  961. /// </summary>
  962. public void Print() {
  963. UniWebViewInterface.Print(listener.name);
  964. }
  965. void OnDestroy() {
  966. UniWebViewNativeListener.RemoveListener(listener.Name);
  967. UniWebViewInterface.Destroy(listener.Name);
  968. Destroy(listener.gameObject);
  969. }
  970. void OnApplicationPause(bool pause) {
  971. #if UNITY_ANDROID && !UNITY_EDITOR
  972. UniWebViewInterface.ShowWebViewDialog(listener.Name, !pause);
  973. #endif
  974. }
  975. /* //////////////////////////////////////////////////////
  976. // Internal Listener Interface
  977. ////////////////////////////////////////////////////// */
  978. internal void InternalOnShowTransitionFinished(string identifier) {
  979. Action action;
  980. if (actions.TryGetValue(identifier, out action)) {
  981. action();
  982. actions.Remove(identifier);
  983. }
  984. }
  985. internal void InternalOnHideTransitionFinished(string identifier) {
  986. Action action;
  987. if (actions.TryGetValue(identifier, out action)) {
  988. action();
  989. actions.Remove(identifier);
  990. }
  991. }
  992. internal void InternalOnAnimateToFinished(string identifier) {
  993. Action action;
  994. if (actions.TryGetValue(identifier, out action)) {
  995. action();
  996. actions.Remove(identifier);
  997. }
  998. }
  999. internal void InternalOnAddJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  1000. Action<UniWebViewNativeResultPayload> action;
  1001. var identifier = payload.identifier;
  1002. if (payloadActions.TryGetValue(identifier, out action)) {
  1003. action(payload);
  1004. payloadActions.Remove(identifier);
  1005. }
  1006. }
  1007. internal void InternalOnEvalJavaScriptFinished(UniWebViewNativeResultPayload payload) {
  1008. Action<UniWebViewNativeResultPayload> action;
  1009. var identifier = payload.identifier;
  1010. if (payloadActions.TryGetValue(identifier, out action)) {
  1011. action(payload);
  1012. payloadActions.Remove(identifier);
  1013. }
  1014. }
  1015. internal void InternalOnPageFinished(UniWebViewNativeResultPayload payload) {
  1016. if (OnPageFinished != null) {
  1017. int code = -1;
  1018. if (int.TryParse(payload.resultCode, out code)) {
  1019. OnPageFinished(this, code, payload.data);
  1020. } else {
  1021. UniWebViewLogger.Instance.Critical("Invalid status code received: " + payload.resultCode);
  1022. }
  1023. }
  1024. }
  1025. internal void InternalOnPageStarted(string url) {
  1026. if (OnPageStarted != null) {
  1027. OnPageStarted(this, url);
  1028. }
  1029. }
  1030. internal void InternalOnPageErrorReceived(UniWebViewNativeResultPayload payload) {
  1031. if (OnPageErrorReceived != null) {
  1032. int code = -1;
  1033. if (int.TryParse(payload.resultCode, out code)) {
  1034. OnPageErrorReceived(this, code, payload.data);
  1035. } else {
  1036. UniWebViewLogger.Instance.Critical("Invalid error code received: " + payload.resultCode);
  1037. }
  1038. }
  1039. }
  1040. internal void InternalOnMessageReceived(string result) {
  1041. var message = new UniWebViewMessage(result);
  1042. if (OnMessageReceived != null) {
  1043. OnMessageReceived(this, message);
  1044. }
  1045. }
  1046. internal void InternalOnWebViewKeyDown(int keyCode) {
  1047. if (OnKeyCodeReceived != null) {
  1048. OnKeyCodeReceived(this, keyCode);
  1049. }
  1050. }
  1051. internal void InternalOnShouldClose() {
  1052. if (OnShouldClose != null) {
  1053. var shouldClose = OnShouldClose(this);
  1054. if (shouldClose) {
  1055. Destroy(this);
  1056. }
  1057. } else {
  1058. Destroy(this);
  1059. }
  1060. }
  1061. internal void InternalWebContentProcessDidTerminate() {
  1062. if (OnWebContentProcessTerminated != null) {
  1063. OnWebContentProcessTerminated(this);
  1064. }
  1065. }
  1066. [Obsolete("OreintationChangedDelegate is a typo and deprecated. Use `OrientationChangedDelegate` instead.", true)]
  1067. public delegate void OreintationChangedDelegate(UniWebView webView, ScreenOrientation orientation);
  1068. [Obsolete("OnOreintationChanged is a typo and deprecated. Use `OnOrientationChanged` instead.", true)]
  1069. #pragma warning disable CS0067
  1070. public event OrientationChangedDelegate OnOreintationChanged;
  1071. }