BaseWebView.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. // Copyright (c) 2022 Vuplex Inc. All rights reserved.
  2. //
  3. // Licensed under the Vuplex Commercial Software Library License, you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // https://vuplex.com/commercial-library-license
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Only define BaseWebView.cs on supported platforms to avoid IL2CPP linking
  15. // errors on unsupported platforms.
  16. #if UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX || UNITY_ANDROID || (UNITY_IOS && !VUPLEX_OMIT_IOS) || (UNITY_WEBGL && !VUPLEX_OMIT_WEBGL) || UNITY_WSA
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Globalization;
  20. using System.IO;
  21. using System.Linq;
  22. using System.Runtime.InteropServices;
  23. using System.Text.RegularExpressions;
  24. using System.Threading.Tasks;
  25. using UnityEngine;
  26. using Vuplex.WebView.Internal;
  27. namespace Vuplex.WebView {
  28. /// <summary>
  29. /// The base IWebView implementation, which is extended for each platform.
  30. /// </summary>
  31. public abstract class BaseWebView : MonoBehaviour {
  32. public event EventHandler CloseRequested;
  33. public event EventHandler<ConsoleMessageEventArgs> ConsoleMessageLogged {
  34. add {
  35. _consoleMessageLogged += value;
  36. if (_consoleMessageLogged != null && _consoleMessageLogged.GetInvocationList().Length == 1) {
  37. _setConsoleMessageEventsEnabled(true);
  38. }
  39. }
  40. remove {
  41. _consoleMessageLogged -= value;
  42. if (_consoleMessageLogged == null) {
  43. _setConsoleMessageEventsEnabled(false);
  44. }
  45. }
  46. }
  47. public event EventHandler<FocusedInputFieldChangedEventArgs> FocusedInputFieldChanged {
  48. add {
  49. _focusedInputFieldChanged += value;
  50. if (_focusedInputFieldChanged != null && _focusedInputFieldChanged.GetInvocationList().Length == 1) {
  51. _setFocusedInputFieldEventsEnabled(true);
  52. }
  53. }
  54. remove {
  55. _focusedInputFieldChanged -= value;
  56. if (_focusedInputFieldChanged == null) {
  57. _setFocusedInputFieldEventsEnabled(false);
  58. }
  59. }
  60. }
  61. public event EventHandler<ProgressChangedEventArgs> LoadProgressChanged;
  62. public event EventHandler<EventArgs<string>> MessageEmitted;
  63. public event EventHandler PageLoadFailed;
  64. public event EventHandler<EventArgs<string>> TitleChanged;
  65. public event EventHandler<UrlChangedEventArgs> UrlChanged;
  66. public bool IsDisposed { get; protected set; }
  67. public bool IsInitialized { get { return _initState == InitState.Initialized; }}
  68. public List<string> PageLoadScripts { get; } = new List<string>();
  69. public Vector2Int Size { get; private set; }
  70. public Texture2D Texture { get; protected set; }
  71. public string Title { get; private set; } = "";
  72. public string Url { get; private set; } = "";
  73. public virtual Task<bool> CanGoBack() {
  74. _assertValidState();
  75. var taskSource = new TaskCompletionSource<bool>();
  76. _pendingCanGoBackCallbacks.Add(taskSource.SetResult);
  77. WebView_canGoBack(_nativeWebViewPtr);
  78. return taskSource.Task;
  79. }
  80. public virtual Task<bool> CanGoForward() {
  81. _assertValidState();
  82. var taskSource = new TaskCompletionSource<bool>();
  83. _pendingCanGoForwardCallbacks.Add(taskSource.SetResult);
  84. WebView_canGoForward(_nativeWebViewPtr);
  85. return taskSource.Task;
  86. }
  87. public virtual Task<byte[]> CaptureScreenshot() {
  88. var texture = _getReadableTexture();
  89. var bytes = ImageConversion.EncodeToPNG(texture);
  90. Destroy(texture);
  91. return Task.FromResult(bytes);
  92. }
  93. public virtual void Click(int xInPixels, int yInPixels, bool preventStealingFocus = false) {
  94. _assertValidState();
  95. _assertPointIsWithinBounds(xInPixels, yInPixels);
  96. // On most platforms, the regular Click() method doesn't steal focus,
  97. // So, the default is to ignore preventStealingFocus.
  98. WebView_click(_nativeWebViewPtr, xInPixels, yInPixels);
  99. }
  100. public void Click(Vector2 normalizedPoint, bool preventStealingFocus = false) {
  101. _assertValidState();
  102. var pixelsPoint = _convertNormalizedToPixels(normalizedPoint);
  103. Click(pixelsPoint.x, pixelsPoint.y, preventStealingFocus);
  104. }
  105. public virtual async void Copy() {
  106. _assertValidState();
  107. GUIUtility.systemCopyBuffer = await _getSelectedText();
  108. }
  109. public virtual Material CreateMaterial() {
  110. var material = VXUtils.CreateDefaultMaterial();
  111. material.mainTexture = Texture;
  112. return material;
  113. }
  114. public virtual async void Cut() {
  115. _assertValidState();
  116. GUIUtility.systemCopyBuffer = await _getSelectedText();
  117. SendKey("Backspace");
  118. }
  119. public virtual void Dispose() {
  120. _assertValidState();
  121. IsDisposed = true;
  122. WebView_destroy(_nativeWebViewPtr);
  123. _nativeWebViewPtr = IntPtr.Zero;
  124. // To avoid a MissingReferenceException, verify that this script
  125. // hasn't already been destroyed prior to accessing gameObject.
  126. if (this != null) {
  127. Destroy(gameObject);
  128. }
  129. }
  130. public Task<string> ExecuteJavaScript(string javaScript) {
  131. var taskSource = new TaskCompletionSource<string>();
  132. ExecuteJavaScript(javaScript, taskSource.SetResult);
  133. return taskSource.Task;
  134. }
  135. public virtual void ExecuteJavaScript(string javaScript, Action<string> callback) {
  136. _assertValidState();
  137. string resultCallbackId = null;
  138. if (callback != null) {
  139. resultCallbackId = Guid.NewGuid().ToString();
  140. _pendingJavaScriptResultCallbacks[resultCallbackId] = callback;
  141. }
  142. WebView_executeJavaScript(_nativeWebViewPtr, javaScript, resultCallbackId);
  143. }
  144. public virtual Task<byte[]> GetRawTextureData() {
  145. var texture = _getReadableTexture();
  146. var bytes = texture.GetRawTextureData();
  147. Destroy(texture);
  148. return Task.FromResult(bytes);
  149. }
  150. public virtual void GoBack() {
  151. _assertValidState();
  152. WebView_goBack(_nativeWebViewPtr);
  153. }
  154. public virtual void GoForward() {
  155. _assertValidState();
  156. WebView_goForward(_nativeWebViewPtr);
  157. }
  158. public virtual void LoadHtml(string html) {
  159. _assertValidState();
  160. WebView_loadHtml(_nativeWebViewPtr, html);
  161. }
  162. public virtual void LoadUrl(string url) {
  163. _assertValidState();
  164. WebView_loadUrl(_nativeWebViewPtr, _transformUrlIfNeeded(url));
  165. }
  166. public virtual void LoadUrl(string url, Dictionary<string, string> additionalHttpHeaders) {
  167. _assertValidState();
  168. if (additionalHttpHeaders == null) {
  169. LoadUrl(url);
  170. } else {
  171. var headerStrings = additionalHttpHeaders.Keys.Select(key => $"{key}: {additionalHttpHeaders[key]}").ToArray();
  172. var newlineDelimitedHttpHeaders = String.Join("\n", headerStrings);
  173. WebView_loadUrlWithHeaders(_nativeWebViewPtr, url, newlineDelimitedHttpHeaders);
  174. }
  175. }
  176. public Vector2Int NormalizedToPoint(Vector2 normalizedPoint) {
  177. return new Vector2Int((int)(normalizedPoint.x * (float)Size.x), (int)(normalizedPoint.y * (float)Size.y));
  178. }
  179. public virtual void Paste() {
  180. _assertValidState();
  181. var text = GUIUtility.systemCopyBuffer;
  182. foreach (var character in text) {
  183. SendKey(char.ToString(character));
  184. }
  185. }
  186. public Vector2 PointToNormalized(int xInPixels, int yInPixels) {
  187. return new Vector2((float)xInPixels / (float)Size.x, (float)yInPixels / (float)Size.y);
  188. }
  189. public virtual void PostMessage(string message) {
  190. var escapedString = message.Replace("\\", "\\\\")
  191. .Replace("'", "\\\\'")
  192. .Replace("\n", "\\\\n");
  193. ExecuteJavaScript($"vuplex._emit('message', {{ data: \'{escapedString}\' }})", null);
  194. }
  195. public virtual void Reload() {
  196. _assertValidState();
  197. WebView_reload(_nativeWebViewPtr);
  198. }
  199. public virtual void Resize(int width, int height) {
  200. if (width == Size.x && height == Size.y) {
  201. return;
  202. }
  203. _assertValidState();
  204. _assertValidSize(width, height);
  205. VXUtils.ThrowExceptionIfAbnormallyLarge(width, height);
  206. Size = new Vector2Int(width, height);
  207. _resize();
  208. }
  209. public virtual void Scroll(int scrollDeltaXInPixels, int scrollDeltaYInPixels) {
  210. _assertValidState();
  211. WebView_scroll(_nativeWebViewPtr, scrollDeltaXInPixels, scrollDeltaYInPixels);
  212. }
  213. public void Scroll(Vector2 normalizedScrollDelta) {
  214. _assertValidState();
  215. var scrollDeltaInPixels = _convertNormalizedToPixels(normalizedScrollDelta, false);
  216. Scroll(scrollDeltaInPixels.x, scrollDeltaInPixels.y);
  217. }
  218. public virtual void Scroll(Vector2 normalizedScrollDelta, Vector2 normalizedPoint) {
  219. _assertValidState();
  220. var scrollDeltaInPixels = _convertNormalizedToPixels(normalizedScrollDelta, false);
  221. var pointInPixels = _convertNormalizedToPixels(normalizedPoint);
  222. WebView_scrollAtPoint(_nativeWebViewPtr, scrollDeltaInPixels.x, scrollDeltaInPixels.y, pointInPixels.x, pointInPixels.y);
  223. }
  224. public virtual void SelectAll() {
  225. _assertValidState();
  226. // If the focused element is an input with a select() method, then use that.
  227. // Otherwise, travel up the DOM until we get to the body or a contenteditable
  228. // element, and then select its contents.
  229. ExecuteJavaScript(
  230. @"(function() {
  231. var element = document.activeElement || document.body;
  232. while (!(element === document.body || element.getAttribute('contenteditable') === 'true')) {
  233. if (typeof element.select === 'function') {
  234. element.select();
  235. return;
  236. }
  237. element = element.parentElement;
  238. }
  239. var range = document.createRange();
  240. range.selectNodeContents(element);
  241. var selection = window.getSelection();
  242. selection.removeAllRanges();
  243. selection.addRange(range);
  244. })();",
  245. null
  246. );
  247. }
  248. public virtual void SendKey(string key) {
  249. _assertValidState();
  250. WebView_sendKey(_nativeWebViewPtr, key);
  251. }
  252. public static void SetCameraAndMicrophoneEnabled(bool enabled) => WebView_setCameraAndMicrophoneEnabled(enabled);
  253. public virtual void SetFocused(bool focused) {
  254. _assertValidState();
  255. WebView_setFocused(_nativeWebViewPtr, focused);
  256. }
  257. public virtual void SetRenderingEnabled(bool enabled) {
  258. _assertValidState();
  259. WebView_setRenderingEnabled(_nativeWebViewPtr, enabled);
  260. _renderingEnabled = enabled;
  261. if (enabled && _currentNativeTexture != IntPtr.Zero) {
  262. Texture.UpdateExternalTexture(_currentNativeTexture);
  263. }
  264. }
  265. public virtual void StopLoad() {
  266. _assertValidState();
  267. WebView_stopLoad(_nativeWebViewPtr);
  268. }
  269. public Task WaitForNextPageLoadToFinish() {
  270. if (_pageLoadFinishedTaskSource == null) {
  271. _pageLoadFinishedTaskSource = new TaskCompletionSource<bool>();
  272. }
  273. return _pageLoadFinishedTaskSource.Task;
  274. }
  275. public virtual void ZoomIn() {
  276. _assertValidState();
  277. WebView_zoomIn(_nativeWebViewPtr);
  278. }
  279. public virtual void ZoomOut() {
  280. _assertValidState();
  281. WebView_zoomOut(_nativeWebViewPtr);
  282. }
  283. #region Non-public members
  284. protected enum InitState {
  285. Uninitialized,
  286. InProgress,
  287. Initialized
  288. }
  289. EventHandler<ConsoleMessageEventArgs> _consoleMessageLogged;
  290. protected IntPtr _currentNativeTexture;
  291. #if (UNITY_STANDALONE_WIN && !UNITY_EDITOR) || UNITY_EDITOR_WIN
  292. protected const string _dllName = "VuplexWebViewWindows";
  293. #elif (UNITY_STANDALONE_OSX && !UNITY_EDITOR) || UNITY_EDITOR_OSX
  294. protected const string _dllName = "VuplexWebViewMac";
  295. #elif UNITY_WSA
  296. protected const string _dllName = "VuplexWebViewUwp";
  297. #elif UNITY_ANDROID
  298. protected const string _dllName = "VuplexWebViewAndroid";
  299. #else
  300. protected const string _dllName = "__Internal";
  301. #endif
  302. EventHandler<FocusedInputFieldChangedEventArgs> _focusedInputFieldChanged;
  303. protected InitState _initState = InitState.Uninitialized;
  304. protected TaskCompletionSource<bool> _initTaskSource;
  305. Material _materialForBlitting;
  306. protected Vector2Int _native2DPosition; // Used for Native 2D Mode.
  307. protected IntPtr _nativeWebViewPtr;
  308. TaskCompletionSource<bool> _pageLoadFinishedTaskSource;
  309. List<Action<bool>> _pendingCanGoBackCallbacks = new List<Action<bool>>();
  310. List<Action<bool>> _pendingCanGoForwardCallbacks = new List<Action<bool>>();
  311. protected Dictionary<string, Action<string>> _pendingJavaScriptResultCallbacks = new Dictionary<string, Action<string>>();
  312. protected bool _renderingEnabled = true;
  313. // Used for Native 2D Mode. Use Size as the single source of truth for the size
  314. // to ensure that both Size and Rect stay in sync when Resize() or SetRect() is called.
  315. protected Rect _rect {
  316. get { return new Rect(_native2DPosition, Size); }
  317. set {
  318. Size = new Vector2Int((int)value.width, (int)value.height);
  319. _native2DPosition = new Vector2Int((int)value.x, (int)value.y);
  320. }
  321. }
  322. static readonly Regex _streamingAssetsUrlRegex = new Regex(@"^streaming-assets:(//)?(.*)$", RegexOptions.IgnoreCase);
  323. protected void _assertPointIsWithinBounds(int xInPixels, int yInPixels) {
  324. var isValid = xInPixels >= 0 && xInPixels <= Size.x && yInPixels >= 0 && yInPixels <= Size.y;
  325. if (!isValid) {
  326. throw new ArgumentException($"The point provided ({xInPixels}px, {yInPixels}px) is not within the bounds of the webview (width: {Size.x}px, height: {Size.y}px).");
  327. }
  328. }
  329. protected void _assertSingletonEventHandlerUnset(object handler, string eventName) {
  330. if (handler != null) {
  331. throw new InvalidOperationException(eventName + " supports only one event handler. Please remove the existing handler before adding a new one.");
  332. }
  333. }
  334. void _assertValidSize(int width, int height) {
  335. if (!(width > 0 && height > 0)) {
  336. throw new ArgumentException($"Invalid size: ({width}, {height}). The width and height must both be greater than 0.");
  337. }
  338. }
  339. protected void _assertValidState() {
  340. if (!IsInitialized) {
  341. throw new InvalidOperationException("Methods cannot be called on an uninitialized webview. Prior to calling the webview's methods, please initialize it first by calling IWebView.Init() and awaiting the Task it returns.");
  342. }
  343. if (IsDisposed) {
  344. throw new InvalidOperationException("Methods cannot be called on a disposed webview.");
  345. }
  346. }
  347. protected Vector2Int _convertNormalizedToPixels(Vector2 normalizedPoint, bool assertBetweenZeroAndOne = true) {
  348. if (assertBetweenZeroAndOne) {
  349. var isValid = normalizedPoint.x >= 0f && normalizedPoint.x <= 1f && normalizedPoint.y >= 0f && normalizedPoint.y <= 1f;
  350. if (!isValid) {
  351. throw new ArgumentException($"The normalized point provided is invalid. The x and y values of normalized points must be in the range of [0, 1], but the value provided was {normalizedPoint.ToString("n4")}. For more info, please see https://support.vuplex.com/articles/normalized-points");
  352. }
  353. }
  354. return new Vector2Int((int)(normalizedPoint.x * Size.x), (int)(normalizedPoint.y * Size.y));
  355. }
  356. protected virtual Task<Texture2D> _createTexture(int width, int height) {
  357. VXUtils.ThrowExceptionIfAbnormallyLarge(width, height);
  358. var texture = new Texture2D(
  359. width,
  360. height,
  361. TextureFormat.RGBA32,
  362. false,
  363. false
  364. );
  365. #if UNITY_2020_2_OR_NEWER
  366. // In Unity 2020.2, Unity's internal TexturesD3D11.cpp class on Windows logs an error if
  367. // UpdateExternalTexture() is called on a Texture2D created from the constructor
  368. // rather than from Texture2D.CreateExternalTexture(). So, rather than returning
  369. // the original Texture2D created via the constructor, we return a copy created
  370. // via CreateExternalTexture(). This approach is only used for 2020.2 and newer because
  371. // it doesn't work in 2018.4 and instead causes a crash.
  372. texture = Texture2D.CreateExternalTexture(
  373. width,
  374. height,
  375. TextureFormat.RGBA32,
  376. false,
  377. false,
  378. texture.GetNativeTexturePtr()
  379. );
  380. #endif
  381. return Task.FromResult(texture);
  382. }
  383. protected virtual void _destroyNativeTexture(IntPtr nativeTexture) {
  384. WebView_destroyTexture(nativeTexture, SystemInfo.graphicsDeviceType.ToString());
  385. }
  386. Texture2D _getReadableTexture() {
  387. // https://support.unity3d.com/hc/en-us/articles/206486626-How-can-I-get-pixels-from-unreadable-textures-
  388. RenderTexture tempRenderTexture = RenderTexture.GetTemporary(
  389. Size.x,
  390. Size.y,
  391. 0,
  392. RenderTextureFormat.Default,
  393. RenderTextureReadWrite.Linear
  394. );
  395. RenderTexture previousRenderTexture = RenderTexture.active;
  396. RenderTexture.active = tempRenderTexture;
  397. // Explicitly clear the temporary render texture, otherwise it can contain
  398. // existing content that won't be overwritten by transparent pixels.
  399. GL.Clear(true, true, Color.clear);
  400. // Use the version of Graphics.Blit() that accepts a material
  401. // so that any transformations needed are performed with the shader.
  402. if (_materialForBlitting == null) {
  403. _materialForBlitting = VXUtils.CreateDefaultMaterial();
  404. }
  405. Graphics.Blit(Texture, tempRenderTexture, _materialForBlitting);
  406. Texture2D readableTexture = new Texture2D(Size.x, Size.y);
  407. readableTexture.ReadPixels(new Rect(0, 0, tempRenderTexture.width, tempRenderTexture.height), 0, 0);
  408. readableTexture.Apply();
  409. RenderTexture.active = previousRenderTexture;
  410. RenderTexture.ReleaseTemporary(tempRenderTexture);
  411. return readableTexture;
  412. }
  413. Task<string> _getSelectedText() {
  414. // window.getSelection() doesn't work on the content of <textarea> and <input> elements in
  415. // Gecko and legacy Edge.
  416. // https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection#Related_objects
  417. return ExecuteJavaScript(
  418. @"var element = document.activeElement;
  419. if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {
  420. element.value.substring(element.selectionStart, element.selectionEnd);
  421. } else {
  422. window.getSelection().toString();
  423. }"
  424. );
  425. }
  426. // Invoked by the native plugin.
  427. void HandleCanGoBackResult(string message) {
  428. var result = Boolean.Parse(message);
  429. var callbacks = new List<Action<bool>>(_pendingCanGoBackCallbacks);
  430. _pendingCanGoBackCallbacks.Clear();
  431. foreach (var callback in callbacks) {
  432. try {
  433. callback(result);
  434. } catch (Exception e) {
  435. WebViewLogger.LogError("An exception occurred while calling the callback for CanGoBack: " + e);
  436. }
  437. }
  438. }
  439. // Invoked by the native plugin.
  440. void HandleCanGoForwardResult(string message) {
  441. var result = Boolean.Parse(message);
  442. var callBacks = new List<Action<bool>>(_pendingCanGoForwardCallbacks);
  443. _pendingCanGoForwardCallbacks.Clear();
  444. foreach (var callBack in callBacks) {
  445. try {
  446. callBack(result);
  447. } catch (Exception e) {
  448. WebViewLogger.LogError("An exception occurred while calling the callForward for CanGoForward: " + e);
  449. }
  450. }
  451. }
  452. // Invoked by the native plugin.
  453. void HandleCloseRequested(string message) => CloseRequested?.Invoke(this, EventArgs.Empty);
  454. // Invoked by the native plugin.
  455. void HandleInitFinished(string unusedParam) {
  456. _initState = InitState.Initialized;
  457. _initTaskSource.SetResult(true);
  458. _initTaskSource = null;
  459. }
  460. // Invoked by the native plugin.
  461. void HandleJavaScriptResult(string message) {
  462. var components = message.Split(new char[] { ',' }, 2);
  463. var resultCallbackId = components[0];
  464. var result = components[1];
  465. _handleJavaScriptResult(resultCallbackId, result);
  466. }
  467. void _handleJavaScriptResult(string resultCallbackId, string result) {
  468. var callback = _pendingJavaScriptResultCallbacks[resultCallbackId];
  469. _pendingJavaScriptResultCallbacks.Remove(resultCallbackId);
  470. callback(result);
  471. }
  472. // Invoked by the native plugin.
  473. void HandleLoadFailed(string unusedParam) {
  474. PageLoadFailed?.Invoke(this, EventArgs.Empty);
  475. OnLoadProgressChanged(new ProgressChangedEventArgs(ProgressChangeType.Failed, 1.0f));
  476. _pageLoadFinishedTaskSource?.SetException(new PageLoadFailedException("The current web page failed to load."));
  477. _pageLoadFinishedTaskSource = null;
  478. if (PageLoadFailed == null && LoadProgressChanged == null) {
  479. // No handlers are attached to PageLoadFailed or LoadProgressChanged,
  480. // so log a warning about the page load failure.
  481. WebViewLogger.LogWarning("A web page failed to load. This can happen if the URL loaded is invalid or if the device has no network connection. To detect and handle page load failures like this, applications can use the IWebView.LoadProgressChanged event or the IWebView.PageLoadFailed event.");
  482. }
  483. }
  484. // Invoked by the native plugin.
  485. void HandleLoadFinished(string unusedParam) {
  486. OnLoadProgressChanged(new ProgressChangedEventArgs(ProgressChangeType.Finished, 1.0f));
  487. _pageLoadFinishedTaskSource?.SetResult(true);
  488. _pageLoadFinishedTaskSource = null;
  489. foreach (var script in PageLoadScripts) {
  490. ExecuteJavaScript(script, null);
  491. }
  492. }
  493. // Invoked by the native plugin.
  494. void HandleLoadStarted(string unusedParam) {
  495. OnLoadProgressChanged(new ProgressChangedEventArgs(ProgressChangeType.Started, 0.0f));
  496. }
  497. // Invoked by the native plugin.
  498. void HandleLoadProgressUpdate(string progressString) {
  499. var progress = float.Parse(progressString, CultureInfo.InvariantCulture);
  500. OnLoadProgressChanged(new ProgressChangedEventArgs(ProgressChangeType.Updated, progress));
  501. }
  502. // Invoked by the native plugin.
  503. protected virtual void HandleMessageEmitted(string serializedMessage) {
  504. // For performance, only try to deserialize the message if it's one we're listening for.
  505. var messageType = serializedMessage.Contains("vuplex.webview") ? BridgeMessage.ParseType(serializedMessage) : null;
  506. switch (messageType) {
  507. case "vuplex.webview.consoleMessageLogged": {
  508. var consoleMessage = JsonUtility.FromJson<ConsoleBridgeMessage>(serializedMessage);
  509. _consoleMessageLogged?.Invoke(this, consoleMessage.ToEventArgs());
  510. break;
  511. }
  512. case "vuplex.webview.focusedInputFieldChanged": {
  513. var typeString = StringBridgeMessage.ParseValue(serializedMessage);
  514. var type = FocusedInputFieldChangedEventArgs.ParseType(typeString);
  515. _focusedInputFieldChanged?.Invoke(this, new FocusedInputFieldChangedEventArgs(type));
  516. break;
  517. }
  518. case "vuplex.webview.javaScriptResult": {
  519. var message = JsonUtility.FromJson<StringWithIdBridgeMessage>(serializedMessage);
  520. _handleJavaScriptResult(message.id, message.value);
  521. break;
  522. }
  523. case "vuplex.webview.titleChanged": {
  524. Title = StringBridgeMessage.ParseValue(serializedMessage);
  525. TitleChanged?.Invoke(this, new EventArgs<string>(Title));
  526. break;
  527. }
  528. case "vuplex.webview.urlChanged": {
  529. var action = JsonUtility.FromJson<UrlChangedMessage>(serializedMessage).urlAction;
  530. if (Url == action.Url) {
  531. return;
  532. }
  533. Url = action.Url;
  534. UrlChanged?.Invoke(this, new UrlChangedEventArgs(action.Url, action.Type));
  535. break;
  536. }
  537. default: {
  538. MessageEmitted?.Invoke(this, new EventArgs<string>(serializedMessage));
  539. break;
  540. }
  541. }
  542. }
  543. // Invoked by the native plugin.
  544. virtual protected void HandleTextureChanged(string textureString) {
  545. // Use UInt64.Parse() because Int64.Parse() can result in an OverflowException.
  546. var nativeTexture = new IntPtr((Int64)UInt64.Parse(textureString));
  547. if (nativeTexture == _currentNativeTexture) {
  548. return;
  549. }
  550. var previousNativeTexture = _currentNativeTexture;
  551. _currentNativeTexture = nativeTexture;
  552. if (_renderingEnabled) {
  553. Texture.UpdateExternalTexture(nativeTexture);
  554. }
  555. if (previousNativeTexture != IntPtr.Zero) {
  556. _destroyNativeTexture(previousNativeTexture);
  557. }
  558. }
  559. protected async Task _initBase(int width, int height, bool createTexture = true, bool asyncInit = false) {
  560. if (_initState != InitState.Uninitialized) {
  561. var message = _initState == InitState.Initialized ? "Init() cannot be called on a webview that has already been initialized."
  562. : "Init() cannot be called on a webview that is already in the process of initialization.";
  563. throw new InvalidOperationException(message);
  564. }
  565. _assertValidSize(width, height);
  566. // Assign the game object a unique name so that the native view can send it messages.
  567. gameObject.name = "WebView-" + Guid.NewGuid().ToString();
  568. Size = new Vector2Int(width, height);
  569. VXUtils.ThrowExceptionIfAbnormallyLarge(width, height);
  570. // Prevent the script from automatically being destroyed when a new scene is loaded.
  571. DontDestroyOnLoad(gameObject);
  572. if (createTexture) {
  573. Texture = await _createTexture(width, height);
  574. }
  575. if (asyncInit) {
  576. _initState = InitState.InProgress;
  577. _initTaskSource = new TaskCompletionSource<bool>();
  578. } else {
  579. _initState = InitState.Initialized;
  580. }
  581. }
  582. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
  583. static void _logDeprecationErrorIfNeeded() {
  584. #if !(NET_4_6 || NET_STANDARD_2_0)
  585. WebViewLogger.LogError("Support for the legacy .NET 3.5 runtime was removed in 3D WebView v4.0. Please switch to the .NET 4.x runtime.");
  586. #endif
  587. }
  588. protected virtual void OnLoadProgressChanged(ProgressChangedEventArgs eventArgs) => LoadProgressChanged?.Invoke(this, eventArgs);
  589. protected ConsoleMessageLevel _parseConsoleMessageLevel(string levelString) {
  590. switch (levelString) {
  591. case "DEBUG":
  592. return ConsoleMessageLevel.Debug;
  593. case "ERROR":
  594. return ConsoleMessageLevel.Error;
  595. case "LOG":
  596. return ConsoleMessageLevel.Log;
  597. case "WARNING":
  598. return ConsoleMessageLevel.Warning;
  599. default:
  600. WebViewLogger.LogWarning("Unrecognized console message level: " + levelString);
  601. return ConsoleMessageLevel.Log;
  602. }
  603. }
  604. protected virtual void _resize() => WebView_resize(_nativeWebViewPtr, Size.x, Size.y);
  605. protected virtual void _setConsoleMessageEventsEnabled(bool enabled) {
  606. _assertValidState();
  607. WebView_setConsoleMessageEventsEnabled(_nativeWebViewPtr, enabled);
  608. }
  609. protected virtual void _setFocusedInputFieldEventsEnabled(bool enabled) {
  610. _assertValidState();
  611. WebView_setFocusedInputFieldEventsEnabled(_nativeWebViewPtr, enabled);
  612. }
  613. protected string _transformUrlIfNeeded(string originalUrl) {
  614. if (originalUrl == null) {
  615. throw new ArgumentException("URL cannot be null.");
  616. }
  617. // Default to https:// if no protocol is specified.
  618. if (!originalUrl.Contains(":")) {
  619. if (!originalUrl.Contains(".")) {
  620. // The URL doesn't include a valid domain, so throw instead of defaulting to https://.
  621. throw new ArgumentException("Invalid URL: " + originalUrl);
  622. }
  623. var updatedUrl = "https://" + originalUrl;
  624. WebViewLogger.LogWarning($"The provided URL is missing a protocol (e.g. http://, https://), so it will default to https://. Original URL: {originalUrl}, Updated URL: {updatedUrl}");
  625. return updatedUrl;
  626. }
  627. // If a streaming-assets:// URL was specified, so transform it to a URL that the browser can load.
  628. var streamingAssetsRegexMatch = _streamingAssetsUrlRegex.Match(originalUrl);
  629. if (streamingAssetsRegexMatch.Success) {
  630. var urlPath = streamingAssetsRegexMatch.Groups[2].Captures[0].Value;
  631. // If Application.streamingAssetsPath doesn't already contain a URL protocol, then add
  632. // the file:// protocol. It already has a protocol in the case of WebGL (http(s)://)
  633. // and Android (jar:file://).
  634. var urlProtocolToAdd = Application.streamingAssetsPath.Contains("://") ? "" : "file://";
  635. // Spaces in URLs must be escaped
  636. var streamingAssetsUrl = urlProtocolToAdd + Path.Combine(Application.streamingAssetsPath, urlPath).Replace(" ", "%20");
  637. return streamingAssetsUrl;
  638. }
  639. return originalUrl;
  640. }
  641. [DllImport(_dllName)]
  642. static extern void WebView_canGoBack(IntPtr webViewPtr);
  643. [DllImport(_dllName)]
  644. static extern void WebView_canGoForward(IntPtr webViewPtr);
  645. [DllImport(_dllName)]
  646. protected static extern void WebView_click(IntPtr webViewPtr, int x, int y);
  647. [DllImport(_dllName)]
  648. protected static extern void WebView_destroyTexture(IntPtr texture, string graphicsApi);
  649. [DllImport(_dllName)]
  650. static extern void WebView_destroy(IntPtr webViewPtr);
  651. [DllImport(_dllName)]
  652. static extern void WebView_executeJavaScript(IntPtr webViewPtr, string javaScript, string resultCallbackId);
  653. [DllImport(_dllName)]
  654. static extern void WebView_goBack(IntPtr webViewPtr);
  655. [DllImport(_dllName)]
  656. static extern void WebView_goForward(IntPtr webViewPtr);
  657. [DllImport(_dllName)]
  658. static extern void WebView_sendKey(IntPtr webViewPtr, string input);
  659. [DllImport(_dllName)]
  660. static extern void WebView_loadHtml(IntPtr webViewPtr, string html);
  661. [DllImport(_dllName)]
  662. static extern void WebView_loadUrl(IntPtr webViewPtr, string url);
  663. [DllImport(_dllName)]
  664. static extern void WebView_loadUrlWithHeaders(IntPtr webViewPtr, string url, string newlineDelimitedHttpHeaders);
  665. [DllImport(_dllName)]
  666. static extern void WebView_reload(IntPtr webViewPtr);
  667. [DllImport(_dllName)]
  668. protected static extern void WebView_resize(IntPtr webViewPtr, int width, int height);
  669. [DllImport(_dllName)]
  670. static extern void WebView_scroll(IntPtr webViewPtr, int deltaX, int deltaY);
  671. [DllImport(_dllName)]
  672. static extern void WebView_scrollAtPoint(IntPtr webViewPtr, int deltaX, int deltaY, int pointerX, int pointerY);
  673. [DllImport(_dllName)]
  674. static extern void WebView_setCameraAndMicrophoneEnabled(bool enabled);
  675. [DllImport(_dllName)]
  676. static extern void WebView_setConsoleMessageEventsEnabled(IntPtr webViewPtr, bool enabled);
  677. [DllImport(_dllName)]
  678. static extern void WebView_setFocused(IntPtr webViewPtr, bool focused);
  679. [DllImport(_dllName)]
  680. static extern void WebView_setFocusedInputFieldEventsEnabled(IntPtr webViewPtr, bool enabled);
  681. [DllImport(_dllName)]
  682. static extern void WebView_setRenderingEnabled(IntPtr webViewPtr, bool enabled);
  683. [DllImport(_dllName)]
  684. static extern void WebView_stopLoad(IntPtr webViewPtr);
  685. [DllImport(_dllName)]
  686. static extern void WebView_zoomIn(IntPtr webViewPtr);
  687. [DllImport(_dllName)]
  688. static extern void WebView_zoomOut(IntPtr webViewPtr);
  689. #endregion
  690. #region Obsolete APIs
  691. [Obsolete(ObsoletionMessages.Blur, true)]
  692. public void Blur() {}
  693. [Obsolete(ObsoletionMessages.CanGoBack, true)]
  694. public void CanGoBack(Action<bool> callback) {}
  695. [Obsolete(ObsoletionMessages.CanGoForward, true)]
  696. public void CanGoForward(Action<bool> callback) {}
  697. [Obsolete(ObsoletionMessages.CaptureScreenshot, true)]
  698. public void CaptureScreenshot(Action<byte[]> callback) {}
  699. [Obsolete(ObsoletionMessages.DisableViewUpdates, true)]
  700. public void DisableViewUpdates() {}
  701. [Obsolete(ObsoletionMessages.EnableViewUpdates, true)]
  702. public void EnableViewUpdates() {}
  703. [Obsolete(ObsoletionMessages.Focus, true)]
  704. public void Focus() {}
  705. [Obsolete(ObsoletionMessages.GetRawTextureData, true)]
  706. public void GetRawTextureData(Action<byte[]> callback) {}
  707. [Obsolete(ObsoletionMessages.HandleKeyboardInput)]
  708. public void HandleKeyboardInput(string key) => SendKey(key);
  709. [Obsolete(ObsoletionMessages.Init, true)]
  710. public void Init(Texture2D texture, float width, float height) {}
  711. [Obsolete(ObsoletionMessages.Init2, true)]
  712. public void Init(Texture2D texture, float width, float height, Texture2D videoTexture) {}
  713. [Obsolete(ObsoletionMessages.Resolution, true)]
  714. public float Resolution { get; }
  715. [Obsolete(ObsoletionMessages.SetResolution, true)]
  716. public void SetResolution(float pixelsPerUnityUnit) {}
  717. [Obsolete(ObsoletionMessages.SizeInPixels)]
  718. public Vector2 SizeInPixels { get { return (Vector2)Size; }}
  719. #pragma warning disable CS0067
  720. [Obsolete(ObsoletionMessages.VideoRectChanged, true)]
  721. public event EventHandler<EventArgs<Rect>> VideoRectChanged;
  722. [Obsolete(ObsoletionMessages.VideoTexture, true)]
  723. public Texture2D VideoTexture { get; }
  724. #endregion
  725. }
  726. }
  727. #endif