IWebView.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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. using System;
  15. using System.Collections.Generic;
  16. using System.Threading.Tasks;
  17. using UnityEngine;
  18. namespace Vuplex.WebView {
  19. /// <summary>
  20. /// IWebView is the primary interface for loading and interacting with web content.
  21. /// It contains methods and properties for common browser-related functionality,
  22. /// like LoadUrl(), GoBack(), Reload(), and ExecuteJavaScript().
  23. /// </summary>
  24. /// <remarks>
  25. /// <para>
  26. /// To create an IWebView, instantiate a WebViewPrefab or CanvasWebViewPrefab. After
  27. /// the prefab is initialized, you can access its IWebView via the WebViewPrefab.WebView property.
  28. /// If your use case requires a high degree of customization, you can instead create
  29. /// an IWebView outside of a prefab (to connect to your own custom GameObject) by
  30. /// using Web.CreateWebView().
  31. /// </para>
  32. /// <para>
  33. /// For additional functionality, you can cast an IWebView to an interface for a specific
  34. /// feature, like IWithDownloads or IWithPopups. For a list of additional feature interfaces and
  35. /// information about how to use them, see this page: https://developer.vuplex.com/webview/additional-interfaces
  36. /// </para>
  37. /// See also:
  38. /// <list type="bullet">
  39. /// <item>WebViewPrefab: https://developer.vuplex.com/webview/WebViewPrefab</item>
  40. /// <item>CanvasWebViewPrefab: https://developer.vuplex.com/webview/CanvasWebViewPrefab</item>
  41. /// <item>Web (static methods): https://developer.vuplex.com/webview/Web</item>
  42. /// </list>
  43. /// </remarks>
  44. public interface IWebView {
  45. /// <summary>
  46. /// Indicates that the page has requested to close (i.e. via window.close()).
  47. /// </summary>
  48. /// <example>
  49. /// <code>
  50. /// await webViewPrefab.WaitUntilInitialized();
  51. /// webViewPrefab.WebView.CloseRequested += (sender, eventArgs) => {
  52. /// Debug.Log("Close requested");
  53. /// };
  54. /// </code>
  55. /// </example>
  56. event EventHandler CloseRequested;
  57. /// <summary>
  58. /// Indicates that a message was logged to the JavaScript console.
  59. /// </summary>
  60. /// <remarks>
  61. /// The 3D WebView packages for Android with Gecko, iOS, and UWP have the following limitations:
  62. /// <list type="bullet">
  63. /// <item>
  64. /// Only messages explicitly passed to a console method like console.log() are included,
  65. /// and other messages like uncaught errors or network errors aren't automatically included.
  66. /// </item>
  67. /// <item>Messages from iframes aren't included.</item>
  68. /// <item>Messages logged early when the page starts loading may be missed.</item>
  69. /// </list>
  70. /// For Android Gecko, an alternative that avoids these limitations is to call
  71. /// AndroidGeckoWebView.SetConsoleOutputEnabled().
  72. /// </remarks>
  73. /// <example>
  74. /// <code>
  75. /// await webViewPrefab.WaitUntilInitialized();
  76. /// webViewPrefab.WebView.ConsoleMessageLogged += (sender, eventArgs) => {
  77. /// Debug.Log($"Console message logged: [{eventArgs.Level}] {eventArgs.Message}");
  78. /// };
  79. /// </code>
  80. /// </example>
  81. /// <seealso cref="WebViewPrefab.LogConsoleMessages"/>
  82. /// <seealso href="https://support.vuplex.com/articles/how-to-debug-web-content">Remote debugging</seealso>
  83. event EventHandler<ConsoleMessageEventArgs> ConsoleMessageLogged;
  84. /// <summary>
  85. /// Indicates when an input field has been focused or unfocused. This can be used,
  86. /// for example, to determine when to show or hide an on-screen keyboard.
  87. /// This event is also raised when a focused input field is clicked subsequent times.
  88. /// Note that this event is currently only fired for input fields focused in the main frame
  89. /// and is not fired for input fields in iframes.
  90. /// </summary>
  91. /// <example>
  92. /// <code>
  93. /// await webViewPrefab.WaitUntilInitialized();
  94. /// webViewPrefab.WebView.FocusedInputFieldChanged += (sender, eventArgs) => {
  95. /// Debug.Log("Focused input field changed. Text input is focused: " + eventArgs.Type == FocusedInputFieldType.Text);
  96. /// };
  97. /// </code>
  98. /// </example>
  99. event EventHandler<FocusedInputFieldChangedEventArgs> FocusedInputFieldChanged;
  100. /// <summary>
  101. /// Indicates that the page load progress changed.
  102. /// </summary>
  103. /// <remarks>
  104. /// For 2D WebView for WebGL, LoadProgressChanged only indicates the ProgressChangeType.Started and Finished events,
  105. /// and it's unable to indicate the Failed or Updated events.
  106. /// </remarks>
  107. /// <example>
  108. /// <code>
  109. /// await webViewPrefab.WaitUntilInitialized();
  110. /// webViewPrefab.WebView.LoadProgressChanged += (sender, eventArgs) => {
  111. /// Debug.Log($"Load progress changed: {eventArgs.Type}, {eventArgs.Progress}");
  112. /// if (eventArgs.Type == ProgressChangeType.Finished) {
  113. /// Debug.Log("The page finished loading");
  114. /// }
  115. /// };
  116. /// </code>
  117. /// </example>
  118. /// <seealso cref="WaitForNextPageLoadToFinish"/>
  119. event EventHandler<ProgressChangedEventArgs> LoadProgressChanged;
  120. /// <summary>
  121. /// Indicates that JavaScript running in the page used the `window.vuplex.postMessage`
  122. /// JavaScript API to emit a message to the Unity application. For more details, please see
  123. /// [this support article](https://support.vuplex.com/articles/how-to-send-messages-from-javascript-to-c-sharp).
  124. /// </summary>
  125. /// <example>
  126. /// <code>
  127. /// await webViewPrefab.WaitUntilInitialized();
  128. /// // Add JavaScript to the page that sends a message.
  129. /// webViewPrefab.WebView.PageLoadScripts.Add(@"
  130. /// window.vuplex.postMessage('Hello from JavaScript!');
  131. /// ");
  132. /// webViewPrefab.WebView.MessageEmitted += (sender, eventArgs) => {
  133. /// Debug.Log("Message received from JavaScript: " + eventArgs.Value);
  134. /// };
  135. /// </code>
  136. /// </example>
  137. /// <seealso cref="ExecuteJavaScript"/>
  138. /// <seealso cref="PageLoadScripts"/>
  139. event EventHandler<EventArgs<string>> MessageEmitted;
  140. /// <summary>
  141. /// Indicates that the page failed to load. This can happen, for instance,
  142. /// if DNS is unable to resolve the hostname.
  143. /// </summary>
  144. /// <example>
  145. /// <code>
  146. /// await webViewPrefab.WaitUntilInitialized();
  147. /// webViewPrefab.WebView.PageLoadFailed += (sender, eventArgs) => {
  148. /// Debug.Log("Page load failed");
  149. /// };
  150. /// </code>
  151. /// </example>
  152. event EventHandler PageLoadFailed;
  153. /// <summary>
  154. /// Indicates that the page's title changed.
  155. /// </summary>
  156. /// <example>
  157. /// <code>
  158. /// await webViewPrefab.WaitUntilInitialized();
  159. /// webViewPrefab.WebView.TitleChanged += (sender, eventArgs) => {
  160. /// Debug.Log("Page title changed: " + eventArgs.Value);
  161. /// };
  162. /// </code>
  163. /// </example>
  164. event EventHandler<EventArgs<string>> TitleChanged;
  165. /// <summary>
  166. /// Indicates that the URL of the webview changed, either
  167. /// due to user interaction or JavaScript.
  168. /// </summary>
  169. /// <example>
  170. /// <code>
  171. /// await webViewPrefab.WaitUntilInitialized();
  172. /// webViewPrefab.WebView.UrlChanged += (sender, eventArgs) => {
  173. /// Debug.Log("URL changed: " + eventArgs.Url);
  174. /// };
  175. /// </code>
  176. /// </example>
  177. /// <seealso cref="Url"/>
  178. event EventHandler<UrlChangedEventArgs> UrlChanged;
  179. /// <summary>
  180. /// Gets a value indicating whether the instance has been disposed via Dispose().
  181. /// </summary>
  182. bool IsDisposed { get; }
  183. /// <summary>
  184. /// Gets a value indicating whether the instance has been initialized via Init().
  185. /// </summary>
  186. bool IsInitialized { get; }
  187. /// <summary>
  188. /// Gets a list of JavaScript scripts that are automatically executed in every new page that is loaded.
  189. /// </summary>
  190. /// <remarks>
  191. /// This list is empty by default, but the application can add scripts. When used in conjunction
  192. /// with 3D WebView's [message passing API](https://support.vuplex.com/articles/how-to-send-messages-from-javascript-to-c-sharp),
  193. /// it's possible to modify the browser's behavior in significant ways, similar to creating browser extensions.
  194. /// </remarks>
  195. /// <example>
  196. /// <code>
  197. /// // Add a script that automatically hides all scrollbars.
  198. /// await webViewPrefab.WaitUntilInitialized();
  199. /// webViewPrefab.WebView.PageLoadScripts.Add(@"
  200. /// var styleElement = document.createElement('style');
  201. /// styleElement.innerText = 'body::-webkit-scrollbar { display: none; }';
  202. /// document.head.appendChild(styleElement);
  203. /// ");
  204. /// </code>
  205. /// </example>
  206. /// <seealso cref="ExecuteJavaScript"/>
  207. /// <seealso href="https://support.vuplex.com/articles/how-to-send-messages-from-javascript-to-c-sharp">JS-to-C# message passing</seealso>
  208. List<string> PageLoadScripts { get; }
  209. /// <summary>
  210. /// Gets the instance's plugin type.
  211. /// </summary>
  212. /// <example>
  213. /// <code>
  214. /// await webViewPrefab.WaitUntilInitialized();
  215. /// Debug.Log("Plugin type: " + webViewPrefab.WebView.PluginType);
  216. /// </code>
  217. /// </example>
  218. WebPluginType PluginType { get; }
  219. /// <summary>
  220. /// Gets the webview's size in pixels.
  221. /// </summary>
  222. /// <example>
  223. /// <code>
  224. /// await webViewPrefab.WaitUntilInitialized();
  225. /// Debug.Log("Size: " + webViewPrefab.WebView.Size);
  226. /// </code>
  227. /// </example>
  228. /// <seealso cref="Resize"/>
  229. /// <seealso cref="WebViewPrefab.Resolution"/>
  230. Vector2Int Size { get; }
  231. /// <summary>
  232. /// Gets the texture for the webview's web content, or `null` if running in
  233. /// Native 2D Mode. In order to render the texture, the application must use
  234. /// a Material created with CreateMaterial().
  235. /// </summary>
  236. /// <remarks>
  237. /// <para>
  238. /// This texture is an "external texture" created with
  239. /// Texture2D.CreateExternalTexture(). An undocumented characteristic
  240. /// of external textures in Unity is that not all Texture2D methods work for them.
  241. /// For example, Texture2D.GetRawTextureData() and ImageConversion.EncodeToPNG()
  242. /// fail for external textures. To compensate, the IWebView interface includes
  243. /// its own GetRawTextureData() and CaptureScreenshot() methods to replace them.
  244. /// </para>
  245. /// <para>
  246. /// Another quirk of this texture is that Unity always reports its size as
  247. /// 1300px × 1300px in the editor. In reality, 3D WebView resizes the
  248. /// texture in native code to match the dimensions of the webview, but
  249. /// Unity doesn't provide an API to notify the engine that an external texture's size
  250. /// has changed. So, Unity always reports its size as the initial size that was
  251. /// passed to Texture2D.CreateExternalTexture(), which in 3D WebView's case is
  252. /// 1300px × 1300px.
  253. /// </para>
  254. /// </remarks>
  255. /// <example>
  256. /// <code>
  257. /// await webViewPrefab.WaitUntilInitialized();
  258. /// var material = webViewPrefab.WebView.CreateMaterial();
  259. /// // Note: the material returned by CreateMaterial() already
  260. /// // has its mainTexture set to IWebView.Texture, so setting
  261. /// // it explicitly like this is really only needed if you are
  262. /// // switching a material from one webview's texture to another.
  263. /// material.mainTexture = webViewPrefab.WebView.Texture;
  264. /// </code>
  265. /// </example>
  266. Texture2D Texture { get; }
  267. /// <summary>
  268. /// Gets the current web page title.
  269. /// </summary>
  270. /// <example>
  271. /// <code>
  272. /// // Get the page's title after it finishes loading.
  273. /// await webViewPrefab.WaitUntilInitialized();
  274. /// await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
  275. /// Debug.Log("Page title: " + webViewPrefab.WebView.Title);
  276. /// </code>
  277. /// </example>
  278. /// <seealso cref="TitleChanged"/>
  279. string Title { get; }
  280. /// <summary>
  281. /// Gets the current URL.
  282. /// </summary>
  283. /// <example>
  284. /// <code>
  285. /// // Get the page's URL after it finishes loading.
  286. /// await webViewPrefab.WaitUntilInitialized();
  287. /// await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
  288. /// Debug.Log("Page URL: " + webViewPrefab.WebView.Url);
  289. /// </code>
  290. /// </example>
  291. /// <seealso cref="UrlChanged"/>
  292. string Url { get; }
  293. /// <summary>
  294. /// Checks whether the webview can go back with a call to GoBack().
  295. /// </summary>
  296. /// <example>
  297. /// <c>var canGoBack = await webViewPrefab.CanGoBack();</c>
  298. /// </example>
  299. /// <seealso cref="GoBack"/>
  300. Task<bool> CanGoBack();
  301. /// <summary>
  302. /// Checks whether the webview can go forward with a call to GoForward().
  303. /// </summary>
  304. /// <example>
  305. /// <c>var canGoForward = await webViewPrefab.CanGoForward();</c>
  306. /// </example>
  307. /// <seealso cref="GoForward"/>
  308. Task<bool> CanGoForward();
  309. /// <summary>
  310. /// Returns a PNG image of the content visible in the webview.
  311. /// </summary>
  312. /// <remarks>
  313. /// On iOS, screenshots do not include video content, which appears black.
  314. /// </remarks>
  315. /// <example>
  316. /// <code>
  317. /// // Get a screenshot and write it to a file.
  318. /// var screenshotBytes = await webViewPrefab.WebView.CaptureScreenshot();
  319. /// var filePath = Path.Combine(Application.peristentDataPath, "screenshot.png");
  320. /// File.WriteAllBytes(filePath, screenshotBytes);
  321. /// </code>
  322. /// </example>
  323. /// <seealso href="https://docs.unity3d.com/ScriptReference/ImageConversion.LoadImage.html">ImageConversion.LoadImage()</seealso>
  324. /// <seealso cref="GetRawTextureData"/>
  325. Task<byte[]> CaptureScreenshot();
  326. /// <summary>
  327. /// Clicks at the given coordinates in pixels in the web page, dispatching both a mouse
  328. /// down and a mouse up event.
  329. /// </summary>
  330. /// <example>
  331. /// <code>
  332. /// // Click at (250px, 100px).
  333. /// webViewPrefab.WebView.Click(250, 100);
  334. ///
  335. /// // Click at (50px, 150px) and prevent stealing focus from another webview.
  336. /// webViewPrefab.WebView.Click(50, 150, true);
  337. /// </code>
  338. /// </example>
  339. void Click(int xInPixels, int yInPixels, bool preventStealingFocus = false);
  340. /// <summary>
  341. /// Like Click(int, int, bool?), except it takes a normalized point instead of
  342. /// pixel coordinates.
  343. /// </summary>
  344. /// <example>
  345. /// <code>
  346. /// // Click in the exact center of the page.
  347. /// webViewPrefab.WebView.Click(new Vector2(0.5f, 0.5f));
  348. ///
  349. /// // Click in the upper right quadrant of the page
  350. /// // and prevent stealing focus from another webview.
  351. /// webViewPrefab.WebView.Click(new Vector2(0.75f, 0.25f), true);
  352. /// </code>
  353. /// </example>
  354. void Click(Vector2 normalizedPoint, bool preventStealingFocus = false);
  355. /// <summary>
  356. /// Copies the selected text to the clipboard.
  357. /// </summary>
  358. /// <example>
  359. /// <c>webViewPrefab.WebView.Copy();</c>
  360. /// </example>
  361. /// <seealso cref="Cut"/>
  362. /// <seealso cref="Paste"/>
  363. /// <seealso cref="SelectAll"/>
  364. void Copy();
  365. /// <summary>
  366. /// Creates a Material that can be used to display the webview.
  367. /// The returned material already has the webview's Texture set as its mainTexture.
  368. /// </summary>
  369. /// <remarks>
  370. /// Note that WebViewPrefab and CanvasWebViewPrefab take care of material creation for you, so you only need
  371. /// to call this method directly if you need to create an IWebView instance outside of a prefab with
  372. /// Web.CreateWebView().
  373. /// </remarks>
  374. /// <example>
  375. /// <code>
  376. /// GetComponent&lt;Renderer&gt;().material = webView.CreateMaterial();
  377. /// </code>
  378. /// </example>
  379. Material CreateMaterial();
  380. /// <summary>
  381. /// Copies the selected text to the clipboard and removes it.
  382. /// </summary>
  383. /// <example>
  384. /// <c>webViewPrefab.WebView.Cut();</c>
  385. /// </example>
  386. /// <seealso cref="Copy"/>
  387. /// <seealso cref="Paste"/>
  388. /// <seealso cref="SelectAll"/>
  389. void Cut();
  390. /// <summary>
  391. /// Destroys the webview, releasing all of its resources.
  392. /// </summary>
  393. /// <remarks>
  394. /// If you're using a WebViewPrefab or CanvasWebViewPrefab, please call Destroy() on the prefab instead
  395. /// of calling IWebView.Dispose(). Calling IWebView.Dispose() while the prefab is still using the webview
  396. /// can cause issues.
  397. /// </remarks>
  398. void Dispose();
  399. /// <summary>
  400. /// Executes the given JavaScript in the context of the page and returns the result.
  401. /// </summary>
  402. /// <remarks>
  403. /// In order to run JavaScript, a web page must first be loaded. You can use WaitForNextPageLoadToFinish() or the
  404. /// LoadProgressChanged event to run JavaScript after a page loads.
  405. /// </remarks>
  406. /// <example>
  407. /// <code>
  408. /// await webViewPrefab.WaitUntilInitialized();
  409. /// await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
  410. /// var headerText = await webViewPrefab.WebView.ExecuteJavaScript("document.getElementsByTagName('h1')[0].innerText");
  411. /// Debug.Log("H1 text: " + headerText);
  412. /// </code>
  413. /// </example>
  414. /// <seealso cref="PageLoadScripts"/>
  415. /// <seealso href="https://support.vuplex.com/articles/how-to-send-messages-from-javascript-to-c-sharp">JS-to-C# message passing</seealso>
  416. Task<string> ExecuteJavaScript(string javaScript);
  417. /// <summary>
  418. /// Like the other version of ExecuteJavaScript(), except it uses a callback instead
  419. /// of a Task to return the result. If you don't need the result from executing the JavaScript, you can
  420. /// improve the method's efficiency by passing `null` as the callback argument.
  421. /// </summary>
  422. void ExecuteJavaScript(string javaScript, Action<string> callback);
  423. /// <summary>
  424. /// A replacement for [Texture2D.GetRawTextureData()](https://docs.unity3d.com/ScriptReference/Texture2D.GetRawTextureData.html)
  425. /// for IWebView.Texture.
  426. /// </summary>
  427. /// <remarks>
  428. /// Unity's Texture2D.GetRawTextureData() method currently does not work for textures created with
  429. /// Texture2D.CreateExternalTexture(). So, this method serves as a replacement by providing
  430. /// the equivalent functionality. You can load the bytes returned by this method into another
  431. /// texture using [Texture2D.LoadRawTextureData()](https://docs.unity3d.com/ScriptReference/Texture2D.LoadRawTextureData.html).
  432. /// Note that on iOS, the texture data excludes video content, which appears black.
  433. /// </remarks>
  434. /// <example>
  435. /// <code>
  436. /// var textureData = await webViewPrefab.WebView.GetRawTextureData();
  437. /// var texture = new Texture2D(
  438. /// webView.Size.x,
  439. /// webView.Size.y,
  440. /// TextureFormat.RGBA32,
  441. /// false,
  442. /// false
  443. /// );
  444. /// texture.LoadRawTextureData(textureData);
  445. /// texture.Apply();
  446. /// </code>
  447. /// </example>
  448. /// <seealso href="https://docs.unity3d.com/ScriptReference/Texture2D.LoadRawTextureData.html">Texture2D.GetRawTextureData()</seealso>
  449. /// <seealso cref="CaptureScreenshot"/>
  450. Task<byte[]> GetRawTextureData();
  451. /// <summary>
  452. /// Navigates back to the previous page in the webview's history.
  453. /// </summary>
  454. /// <example>
  455. /// <c>webViewPrefab.WebView.GoBack();</c>
  456. /// </example>
  457. /// <seealso cref="CanGoBack"/>
  458. void GoBack();
  459. /// <summary>
  460. /// Navigates forward to the next page in the webview's history.
  461. /// </summary>
  462. /// <example>
  463. /// <c>webViewPrefab.WebView.GoForward();</c>
  464. /// </example>
  465. /// <seealso cref="CanGoForward"/>
  466. void GoForward();
  467. /// <summary>
  468. /// Asynchronously initializes the webview with the given the dimensions in pixels.
  469. /// </summary>
  470. /// <remarks>
  471. /// Note that you don't need to call this method if you're using one of the prefabs, like WebViewPrefab.
  472. /// You only need to call Init() if you create an IWebView directly with Web.CreateWebView()].
  473. /// Also, this method's signature was [updated in 3D WebView v4](https://support.vuplex.com/articles/v4-changes#init).
  474. /// </remarks>
  475. Task Init(int width, int height);
  476. /// <summary>
  477. /// Loads the web page contained in the given HTML string.
  478. /// </summary>
  479. /// <example>
  480. /// <code>
  481. /// <![CDATA[
  482. /// await webViewPrefab.WaitUntilInitialized();
  483. /// webViewPrefab.WebView.LoadHtml(@"
  484. /// <!DOCTYPE html>
  485. /// <html>
  486. /// <head>
  487. /// <title>Test Page</title>
  488. /// <style>
  489. /// h1 {
  490. /// font-family: Helvetica, Arial, Sans-Serif;
  491. /// }
  492. /// </style>
  493. /// </head>
  494. /// <body>
  495. /// <h1>LoadHtml Example</h1>
  496. /// <script>
  497. /// console.log('This page was loaded!');
  498. /// </script>
  499. /// </body>
  500. /// </html>"
  501. /// );
  502. /// ]]>
  503. /// </code>
  504. /// </example>
  505. /// <seealso cref="LoadUrl"/>
  506. void LoadHtml(string html);
  507. /// <summary>
  508. /// Loads the given URL. Supported URL schemes:
  509. /// - `http://`, `https://` - loads a remote page over HTTP
  510. /// - `streaming-assets://` - loads a local page from StreamingAssets
  511. /// (equivalent to `"file://" + Application.streamingAssetsPath + path`)
  512. /// - `file://` - some platforms support loading arbitrary file URLs
  513. /// </summary>
  514. /// <example>
  515. /// <code>
  516. /// await webViewPrefab.WaitUntilInitialized();
  517. /// webViewPrefab.WebView.LoadUrl("https://vuplex.com");
  518. /// </code>
  519. /// </example>
  520. /// <seealso href="https://support.vuplex.com/articles/how-to-load-local-files">How to load local files</seealso>
  521. /// <seealso cref="LoadHtml"/>
  522. /// <seealso cref="WebViewPrefab.InitialUrl"/>
  523. void LoadUrl(string url);
  524. /// <summary>
  525. /// Like LoadUrl(string url), but also sends the given additional HTTP request headers
  526. /// when loading the URL. The headers are sent for the initial page load request but are not sent
  527. /// for requests for subsequent resources, like linked JavaScript or CSS files.
  528. /// </summary>
  529. /// <remarks>
  530. /// On Windows and macOS, this method cannot be used to set the Accept-Language header.
  531. /// For more info, please see [this article](https://support.vuplex.com/articles/how-to-change-accept-language-header).
  532. /// </remarks>
  533. /// <example>
  534. /// <code>
  535. /// await webViewPrefab.WaitUntilInitialized();
  536. /// webViewPrefab.WebView.LoadUrl("https://vuplex.com", new Dictionary&lt;string, string&gt; {
  537. /// ["Authorization"] = "Basic YWxhZGRpbjpvcGVuc2VzYW1l",
  538. /// ["Cookie"] = "foo=bar"
  539. /// });
  540. /// </code>
  541. /// </example>
  542. void LoadUrl(string url, Dictionary<string, string> additionalHttpHeaders);
  543. /// <summary>
  544. /// Returns a point in pixels for the given normalized point.
  545. /// </summary>
  546. /// <seealso cref="PointToNormalized"/>
  547. Vector2Int NormalizedToPoint(Vector2 normalizedPoint);
  548. /// <summary>
  549. /// Pastes text from the clipboard.
  550. /// </summary>
  551. /// <example>
  552. /// <c>webViewPrefab.WebView.Paste();</c>
  553. /// </example>
  554. /// <seealso cref="Copy"/>
  555. /// <seealso cref="Cut"/>
  556. void Paste();
  557. /// <summary>
  558. /// Returns a normalized point for the given x and y coordinates in pixels.
  559. /// This can be used to create normalized points for APIs that accept them, like MovePointer().
  560. /// </summary>
  561. /// <example>
  562. /// <code>
  563. /// var webView = webViewPrefab.WebView;
  564. /// // Scroll to the right by 50 pixels at (100px, 1300px).
  565. /// webView.Scroll(
  566. /// webView.PointToNormalized(50, 0),
  567. /// webView.PointToNormalized(100, 1300)
  568. /// );
  569. /// </code>
  570. /// </example>
  571. /// <seealso cref="NormalizedToPoint"/>
  572. Vector2 PointToNormalized(int xInPixels, int yInPixels);
  573. /// <summary>
  574. /// Posts a message that JavaScript within the webview can listen for
  575. /// using `window.vuplex.addEventListener('message', function(message) {})`.
  576. /// The provided data string is passed as the data property of the message object.
  577. /// For more details, please see [this support article](https://support.vuplex.com/articles/how-to-send-messages-from-javascript-to-c-sharp).
  578. /// </summary>
  579. /// <example>
  580. /// <code>
  581. /// await webViewPrefab.WebView.WaitUntilInitialized();
  582. /// // Add some JavaScript to the page to receive the message.
  583. /// webViewPrefab.WebView.PageLoadScripts(@"
  584. /// window.vuplex.addEventListener('message', function(event) {
  585. /// console.log('Message received from C#: ' + event.data);
  586. /// });
  587. /// ");
  588. /// // When the page finishes loading, send a message from C# to JavaScript.
  589. /// await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
  590. /// webViewPrefab.WebView.PostMessage("Hello from C#");
  591. /// </code>
  592. /// </example>
  593. void PostMessage(string data);
  594. /// <summary>
  595. /// Reloads the current page.
  596. /// </summary>
  597. /// <example>
  598. /// <c>webViewPrefab.WebView.Reload();</c>
  599. /// </example>
  600. void Reload();
  601. /// <summary>
  602. /// Resizes the webview to the given dimensions in pixels.
  603. /// </summary>
  604. /// <remarks>
  605. /// If you're using WebViewPrefab, you should call WebViewPrefab.Resize() instead.
  606. /// </remarks>
  607. /// <seealso cref="Size"/>
  608. /// <seealso cref="WebViewPrefab.Resolution"/>
  609. void Resize(int width, int height);
  610. /// <summary>
  611. /// Scrolls the top-level document by the given delta in pixels.
  612. /// This method works by calling window.scrollBy(), which works for simple web
  613. /// pages but not for all pages. An alternative is to instead use Scroll(Vector2, Vector2)
  614. /// to scroll at a specific location in the page.
  615. /// </summary>
  616. /// <example>
  617. /// <code>
  618. /// // Scroll down by 50 pixels.
  619. /// webViewPrefab.WebView.Scroll(0, 50);
  620. ///
  621. /// // Scroll to the left by 20 pixels.
  622. /// webViewPrefab.WebView.Scroll(-20, 0);
  623. /// </code>
  624. /// </example>
  625. void Scroll(int scrollDeltaXInPixels, int scrollDeltaYInPixels);
  626. /// <summary>
  627. /// Like Scroll(int, int), but accepts a normalized scroll delta instead of
  628. /// values in pixels.
  629. /// </summary>
  630. /// <example>
  631. /// <code>
  632. /// // Scroll down one quarter of the page.
  633. /// webViewPrefab.WebView.Scroll(new Vector2(0, 0.25f));
  634. /// </code>
  635. /// </example>
  636. void Scroll(Vector2 normalizedScrollDelta);
  637. /// <summary>
  638. /// Scrolls by the given normalized scroll delta at the given normalized pointer position.
  639. /// </summary>
  640. /// <example>
  641. /// <code>
  642. /// var webView = webViewPrefab.WebView;
  643. /// // Scroll down by a quarter of the page in the center of the page
  644. /// webView.Scroll(new Vector2(0, 0.25f), new Vector2(0.5f, 0.5f));
  645. ///
  646. /// // Scroll to the right by 50 pixels at (100px, 1300px).
  647. /// webView.Scroll(
  648. /// webView.PointToNormalized(50, 0),
  649. /// webView.PointToNormalized(100, 1300)
  650. /// );
  651. /// </code>
  652. /// </example>
  653. void Scroll(Vector2 normalizedScrollDelta, Vector2 normalizedPoint);
  654. /// <summary>
  655. /// Selects all text, depending on the page's focused element.
  656. /// </summary>
  657. /// <example>
  658. /// <c>webViewPrefab.WebView.SelectAll();</c>
  659. /// </example>
  660. /// <seealso cref="Copy"/>
  661. void SelectAll();
  662. /// <summary>
  663. /// Dispatches the given keyboard key to the webview.
  664. /// </summary>
  665. /// <param name="key">
  666. /// A key can either be a single character representing
  667. /// a unicode character (e.g. "A", "b", "?") or a [JavaScript key value](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values)
  668. /// (e.g. "ArrowUp", "Enter", "Backspace", "Delete").
  669. /// </param>
  670. /// <example>
  671. /// <code>
  672. /// // Type "Hi!" and then submit the Enter key.
  673. /// webViewPrefab.WebView.SendKey("H");
  674. /// webViewPrefab.WebView.SendKey("i");
  675. /// webViewPrefab.WebView.SendKey("!");
  676. /// webViewPrefab.WebView.SendKey("Enter");
  677. /// </code>
  678. /// </example>
  679. /// <seealso cref="IWithKeyDownAndUp"/>
  680. void SendKey(string key);
  681. /// <summary>
  682. /// Makes the webview take or relinquish focus.
  683. /// </summary>
  684. /// <example>
  685. /// <c>webViewPrefab.WebView.SetFocused(true);</c>
  686. /// </example>
  687. void SetFocused(bool focused);
  688. /// <summary>
  689. /// Enables or disables the webview's ability to render to its texture.
  690. /// By default, a webview renders web content to its texture, but you can
  691. /// use this method to disable or re-enable rendering.
  692. /// </summary>
  693. /// <remarks>
  694. /// This method is ignored when running in [Native 2D Mode](https://support.vuplex.com/articles/native-2d-mode).
  695. /// </remarks>
  696. /// <example>
  697. /// <c>webViewPrefab.WebView.SetRenderingEnabled(false);</c>
  698. /// </example>
  699. void SetRenderingEnabled(bool enabled);
  700. /// <summary>
  701. /// Stops the current page load if one is in progress.
  702. /// </summary>
  703. /// <example>
  704. /// <c>webViewPrefab.WebView.StopLoad();</c>
  705. /// </example>
  706. void StopLoad();
  707. /// <summary>
  708. /// Returns a task that completes when the next page load finishes loading, or
  709. /// throws a PageLoadFailedException if the page load fails.
  710. /// </summary>
  711. /// <example>
  712. /// <code>
  713. /// await webViewPrefab.WaitUntilInitialized();
  714. /// await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
  715. /// Debug.Log("The web page finished loading.");
  716. /// </code>
  717. /// </example>
  718. /// <seealso cref="LoadProgressChanged"/>
  719. Task WaitForNextPageLoadToFinish();
  720. /// <summary>
  721. /// Zooms into the currently loaded web content. Note that the zoom level gets reset when a new page is loaded.
  722. /// </summary>
  723. /// <remarks>
  724. /// On Windows and macOS, adjusting the zoom also affects other webviews viewing the same site,
  725. /// similar to how tabs behave in a desktop browser.
  726. /// </remarks>
  727. /// <example>
  728. /// <code>
  729. /// // Zoom in after the page finishes loading.
  730. /// await webViewPrefab.WaitUntilInitialized();
  731. /// await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
  732. /// webViewPrefab.WebView.ZoomIn();
  733. /// </code>
  734. /// </example>
  735. void ZoomIn();
  736. /// <summary>
  737. /// Zooms back out after a previous call to ZoomIn(). Note that the zoom level gets reset when a new page is loaded.
  738. /// </summary>
  739. /// <remarks>
  740. /// On Windows and macOS, adjusting the zoom also affects other webviews viewing the same site,
  741. /// similar to how tabs behave in a desktop browser.
  742. /// </remarks>
  743. /// <example>
  744. /// <code>
  745. /// // Zoom out after the page finishes loading.
  746. /// await webViewPrefab.WaitUntilInitialized();
  747. /// await webViewPrefab.WebView.WaitForNextPageLoadToFinish();
  748. /// webViewPrefab.WebView.ZoomOut();
  749. /// </code>
  750. /// </example>
  751. void ZoomOut();
  752. #region Obsolete APIs
  753. // Added in v1.0, deprecated in v3.13, removed in v4.0.
  754. [Obsolete(ObsoletionMessages.Blur, true)]
  755. void Blur();
  756. // Added in v1.0, deprecated in v3.16, removed in v4.0.
  757. [Obsolete(ObsoletionMessages.CanGoBack, true)]
  758. void CanGoBack(Action<bool> callback);
  759. // Added in v1.0, deprecated in v3.16, removed in v4.0.
  760. [Obsolete(ObsoletionMessages.CanGoForward, true)]
  761. void CanGoForward(Action<bool> callback);
  762. // Added in v2.4, deprecated in v3.16, removed in v4.0.
  763. [Obsolete(ObsoletionMessages.CaptureScreenshot, true)]
  764. void CaptureScreenshot(Action<byte[]> callback);
  765. [Obsolete(ObsoletionMessages.DisableViewUpdates, true)]
  766. void DisableViewUpdates();
  767. [Obsolete(ObsoletionMessages.EnableViewUpdates, true)]
  768. void EnableViewUpdates();
  769. // Added in v1.0, deprecated in v3.13, removed in v4.0.
  770. [Obsolete(ObsoletionMessages.Focus, true)]
  771. void Focus();
  772. // Added in v2.6, deprecated in v3.16, removed in v4.0.
  773. [Obsolete(ObsoletionMessages.GetRawTextureData, true)]
  774. void GetRawTextureData(Action<byte[]> callback);
  775. // Added in v1.0, deprecated in v4.0.
  776. [Obsolete(ObsoletionMessages.HandleKeyboardInput)]
  777. void HandleKeyboardInput(string key);
  778. // Added in v1.0, removed in v4.0.
  779. [Obsolete(ObsoletionMessages.Init, true)]
  780. void Init(Texture2D texture, float width, float height);
  781. // Added in v1.0, removed in v4.0.
  782. [Obsolete(ObsoletionMessages.Init2, true)]
  783. void Init(Texture2D texture, float width, float height, Texture2D videoTexture);
  784. // Added in v1.0, removed in v4.0.
  785. [Obsolete(ObsoletionMessages.Resolution, true)]
  786. float Resolution { get; }
  787. // Added in v1.0, removed in v4.0.
  788. [Obsolete(ObsoletionMessages.SetResolution, true)]
  789. void SetResolution(float pixelsPerUnityUnit);
  790. // Deprecated in v4.0
  791. [Obsolete(ObsoletionMessages.SizeInPixels)]
  792. Vector2 SizeInPixels { get; }
  793. // Added in v1.0, removed in v4.0.
  794. [Obsolete(ObsoletionMessages.VideoRectChanged, true)]
  795. event EventHandler<EventArgs<Rect>> VideoRectChanged;
  796. // Added in v1.0, removed in v4.0.
  797. [Obsolete(ObsoletionMessages.VideoTexture, true)]
  798. Texture2D VideoTexture { get; }
  799. #endregion
  800. }
  801. static class ObsoletionMessages {
  802. public const string Blur = "IWebView.Blur() has been removed. Please use SetFocused(false) instead: https://developer.vuplex.com/webview/IWebView#SetFocused";
  803. public const string CanGoBack = "The callback-based CanGoBack(Action) version of this method has been removed. Please switch to the Task-based CanGoBack() version instead. If you prefer using a callback instead of awaiting the Task, you can still use a callback like this: CanGoBack().ContinueWith(result => {...})";
  804. public const string CanGoForward = "The callback-based CanGoForward(Action) version of this method has been removed. Please switch to the Task-based CanGoForward() version instead. If you prefer using a callback instead of awaiting the Task, you can still use a callback like this: CanGoForward().ContinueWith(result => {...})";
  805. public const string CaptureScreenshot = "The callback-based CaptureScreenshot(Action) version of this method has been removed. Please switch to the Task-based CaptureScreenshot() version instead. If you prefer using a callback instead of awaiting the Task, you can still use a callback like this: CaptureScreenshot().ContinueWith(result => {...})";
  806. public const string DisableViewUpdates = "DisableViewUpdates() has been removed. Please use SetRenderingEnabled(false) instead: https://developer.vuplex.com/webview/IWebView#SetRenderingEnabled";
  807. public const string EnableViewUpdates = "EnableViewUpdates() has been removed. Please use SetRenderingEnabled(true) instead: https://developer.vuplex.com/webview/IWebView#SetRenderingEnabled";
  808. public const string Focus = "IWebView.Focus() has been removed. Please use SetFocused(false) instead: https://developer.vuplex.com/webview/IWebView#SetFocused";
  809. public const string GetRawTextureData = "The callback-based GetRawTextureData(Action) version of this method has been removed. Please switch to the Task-based GetRawTextureData() version instead. If you prefer using a callback instead of awaiting the Task, you can still use a callback like this: GetRawTextureData().ContinueWith(result => {...})";
  810. public const string HandleKeyboardInput = "IWebView.HandleKeyboardInput() has been renamed to IWebView.SendKey(). Please switch to SendKey().";
  811. public const string Init = "IWebView.Init(Texture2D, float, float) has been removed in v4. Please switch to IWebView.Init(int, int) and await the Task it returns. For more details, please see this article: https://support.vuplex.com/articles/v4-changes#init";
  812. public const string Init2 = "IWebView.Init(Texture2D, float, float, Texture2D) has been removed in v4. Please switch to IWebView.Init(int, int) and await the Task it returns. For more details, please see this article: https://support.vuplex.com/articles/v4-changes#init";
  813. public const string Resolution = "IWebView.Resolution has been removed in v4. Please use WebViewPrefab.Resolution or CanvasWebViewPrefab.Resolution instead. For more details, please see this article: https://support.vuplex.com/articles/v4-changes#resolution";
  814. public const string SetResolution = "IWebView.SetResolution() has been removed in v4. Please set the WebViewPrefab.Resolution or CanvasWebViewPrefab.Resolution property instead. For more details, please see this article: https://support.vuplex.com/articles/v4-changes#resolution";
  815. public const string SizeInPixels = "IWebView.SizeInPixels is now deprecated. Please use IWebView.Size instead: https://developer.vuplex.com/webview/IWebView#Size";
  816. public const string VideoRectChanged = "IWebView.VideoRectChanged has been removed. Please use IWithFallbackVideo.VideoRectChanged instead: https://developer.vuplex.com/webview/IWithFallbackVideo#VideoRectChanged";
  817. public const string VideoTexture = "IWebView.VideoTexture has been removed. Please use IWithFallbackVideo.VideoTexture instead: https://developer.vuplex.com/webview/IWithFallbackVideo#VideoTexture";
  818. }
  819. }