UniWebView.Networking.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. //
  2. // UniWebView.Networking.cs
  3. // Created by Wang Wei (@onevcat) on 2025-04-19.
  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 System;
  18. public partial class UniWebView {
  19. /// <summary>
  20. /// Adds a url scheme to UniWebView message system interpreter.
  21. /// All following url navigation to this scheme will be sent as a message to UniWebView instead.
  22. /// </summary>
  23. /// <param name="scheme">The url scheme to add. It should not contain "://" part. You could even add "http" and/or
  24. /// "https" to prevent all resource loading on the page. "uniwebview" is added by default. Nothing will happen if
  25. /// you try to add a duplicated scheme.</param>
  26. public void AddUrlScheme(string scheme) {
  27. if (scheme == null) {
  28. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  29. return;
  30. }
  31. if (scheme.Contains("://")) {
  32. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  33. return;
  34. }
  35. UniWebViewInterface.AddUrlScheme(listener.Name, scheme);
  36. }
  37. /// <summary>
  38. /// Removes a url scheme from UniWebView message system interpreter.
  39. /// </summary>
  40. /// <param name="scheme">The url scheme to remove. Nothing will happen if the scheme is not in the message system.</param>
  41. public void RemoveUrlScheme(string scheme) {
  42. if (scheme == null) {
  43. UniWebViewLogger.Instance.Critical("The scheme should not be null.");
  44. return;
  45. }
  46. if (scheme.Contains("://")) {
  47. UniWebViewLogger.Instance.Critical("The scheme should not include invalid characters '://'");
  48. return;
  49. }
  50. UniWebViewInterface.RemoveUrlScheme(listener.Name, scheme);
  51. }
  52. /// <summary>
  53. /// Adds a domain to the SSL checking white list.
  54. /// This API is deprecated and no longer grants SSL exceptions.
  55. /// Use <see cref="AddSslPinnedFingerprint"/> instead.
  56. /// </summary>
  57. /// <param name="domain">The domain to add. It should not contain any scheme or path part in url.</param>
  58. [Obsolete("AddSslExceptionDomain is deprecated. Use AddSslPinnedFingerprint instead.", true)]
  59. public void AddSslExceptionDomain(string domain) {
  60. if (domain == null) {
  61. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  62. return;
  63. }
  64. if (domain.Contains("://")) {
  65. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  66. return;
  67. }
  68. UniWebViewInterface.AddSslExceptionDomain(listener.Name, domain);
  69. }
  70. /// <summary>
  71. /// Removes a domain from the SSL checking white list.
  72. /// This API is deprecated and kept for binary compatibility only.
  73. /// </summary>
  74. /// <param name="domain">The domain to remove. It should not contain any scheme or path part in url.</param>
  75. [Obsolete("RemoveSslExceptionDomain is deprecated. Use RemoveSslPinnedFingerprint instead.", true)]
  76. public void RemoveSslExceptionDomain(string domain) {
  77. if (domain == null) {
  78. UniWebViewLogger.Instance.Critical("The domain should not be null.");
  79. return;
  80. }
  81. if (domain.Contains("://")) {
  82. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  83. return;
  84. }
  85. UniWebViewInterface.RemoveSslExceptionDomain(listener.Name, domain);
  86. }
  87. /// <summary>
  88. /// Pins a certificate fingerprint for a domain when handling SSL errors.
  89. /// Only when the presented certificate matches the SHA-256 fingerprint will the page be allowed to load.
  90. /// </summary>
  91. /// <param name="domain">The domain to trust. It should not contain any scheme or path part.</param>
  92. /// <param name="fingerprint">The SHA-256 fingerprint of the expected certificate. Colons are optional.</param>
  93. public void AddSslPinnedFingerprint(string domain, string fingerprint) {
  94. if (string.IsNullOrEmpty(domain)) {
  95. UniWebViewLogger.Instance.Critical("The domain should not be null or empty.");
  96. return;
  97. }
  98. if (domain.Contains("://")) {
  99. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  100. return;
  101. }
  102. if (string.IsNullOrEmpty(fingerprint)) {
  103. UniWebViewLogger.Instance.Critical("The fingerprint should not be null or empty.");
  104. return;
  105. }
  106. UniWebViewInterface.AddSslPinnedFingerprint(listener.Name, domain, fingerprint);
  107. }
  108. /// <summary>
  109. /// Removes a previously pinned certificate fingerprint for a domain.
  110. /// </summary>
  111. /// <param name="domain">The domain whose fingerprint should be removed.</param>
  112. /// <param name="fingerprint">The SHA-256 fingerprint registered earlier.</param>
  113. public void RemoveSslPinnedFingerprint(string domain, string fingerprint) {
  114. if (string.IsNullOrEmpty(domain)) {
  115. UniWebViewLogger.Instance.Critical("The domain should not be null or empty.");
  116. return;
  117. }
  118. if (domain.Contains("://")) {
  119. UniWebViewLogger.Instance.Critical("The domain should not include invalid characters '://'");
  120. return;
  121. }
  122. if (string.IsNullOrEmpty(fingerprint)) {
  123. UniWebViewLogger.Instance.Critical("The fingerprint should not be null or empty.");
  124. return;
  125. }
  126. UniWebViewInterface.RemoveSslPinnedFingerprint(listener.Name, domain, fingerprint);
  127. }
  128. /// <summary>
  129. /// Sets a customized header field for web view requests.
  130. ///
  131. /// The header field will be used for all subsequence request.
  132. /// Pass `null` as value to unset a header field.
  133. ///
  134. /// Some reserved headers like user agent are not be able to override by setting here,
  135. /// use the `SetUserAgent` method for them instead.
  136. /// </summary>
  137. /// <param name="key">The key of customized header field.</param>
  138. /// <param name="value">The value of customized header field. `null` if you want to unset the field.</param>
  139. public void SetHeaderField(string key, string value) {
  140. if (key == null) {
  141. UniWebViewLogger.Instance.Critical("Header key should not be null.");
  142. return;
  143. }
  144. UniWebViewInterface.SetHeaderField(listener.Name, key, value);
  145. }
  146. /// <summary>
  147. /// Sets the user agent used in the web view.
  148. /// If the string is null or empty, the system default value will be used.
  149. /// </summary>
  150. /// <param name="agent">The new user agent string to use.</param>
  151. public void SetUserAgent(string agent) {
  152. UniWebViewInterface.SetUserAgent(listener.Name, agent);
  153. }
  154. /// <summary>
  155. /// Gets the user agent string currently used in web view.
  156. /// If a customized user agent is not set, the default user agent in current platform will be returned.
  157. /// </summary>
  158. /// <returns>The user agent string in use.</returns>
  159. public string GetUserAgent() {
  160. return UniWebViewInterface.GetUserAgent(listener.Name);
  161. }
  162. /// <summary>
  163. /// Sets whether loading a local file is allowed.
  164. ///
  165. /// If set to `false`, any load from a file URL `file://` for `Load` method will be rejected and trigger an
  166. /// `OnLoadingErrorReceived` event. That means you cannot load a web page from any local file. If you do not going to
  167. /// load any local files, setting it to `false` helps to reduce the interface of web view and improve the security.
  168. ///
  169. /// By default, it is `true` and the local file URL loading is allowed.
  170. /// </summary>
  171. /// <param name="flag">Whether the local file access by web view loading is allowed or not.</param>
  172. public void SetAllowFileAccess(bool flag) {
  173. UniWebViewInterface.SetAllowFileAccess(listener.Name, flag);
  174. }
  175. /// <summary>
  176. /// Sets whether file access from file URLs is allowed.
  177. ///
  178. /// By setting with `true`, access to file URLs inside the web view will be enabled and you could access
  179. /// sub-resources or make cross origin requests from local HTML files.
  180. ///
  181. /// On iOS, it uses some "hidden" way by setting `allowFileAccessFromFileURLs` in config preferences for WebKit.
  182. /// So it is possible that it stops working in a future version.
  183. ///
  184. /// On Android, it sets the `WebSettings.setAllowFileAccessFromFileURLs` for the current web view.
  185. /// </summary>
  186. /// <param name="flag">Whether the file access inside web view from file URLs is allowed or not.</param>
  187. public void SetAllowFileAccessFromFileURLs(bool flag) {
  188. UniWebViewInterface.SetAllowFileAccessFromFileURLs(listener.Name, flag);
  189. }
  190. /// <summary>
  191. /// Sets allow universal access from file URLs. By default, on iOS, the `WKWebView` forbids any load of local files
  192. /// through AJAX even when opening a local HTML file. It checks the CORS rules and fails at web view level.
  193. /// This is useful when you want access these files by setting the `allowUniversalAccessFromFileURLs` key of web view
  194. /// configuration.
  195. ///
  196. /// On iOS and macOS Editor. It uses some "hidden" way by setting `allowUniversalAccessFromFileURLs` in config
  197. /// for WebKit. So it is possible that it stops working in a future version.
  198. ///
  199. /// On Android, it sets the `WebSettings.setAllowUniversalAccessFromFileURLs` and any later-created web views uses
  200. /// that value.
  201. /// </summary>
  202. /// <param name="flag">A flag indicates whether the universal access for files are allowed or not.</param>
  203. public static void SetAllowUniversalAccessFromFileURLs(bool flag) {
  204. UniWebViewInterface.SetAllowUniversalAccessFromFileURLs(flag);
  205. }
  206. /// <summary>
  207. /// Sets whether the web view limits navigation to pages within the app’s domain.
  208. ///
  209. /// This only works on iOS 14.0+. For more information, refer to the Apple's documentation:
  210. /// https://developer.apple.com/documentation/webkit/wkwebviewconfiguration/3585117-limitsnavigationstoappbounddomai
  211. /// and the App-Bound Domains page: https://webkit.org/blog/10882/app-bound-domains/
  212. ///
  213. /// This requires additional setup in `WKAppBoundDomains` key in the Info.plist file.
  214. ///
  215. /// On Android, this method does nothing.
  216. /// </summary>
  217. /// <param name="enabled"></param>
  218. public static void SetLimitsNavigationsToAppBoundDomains(bool enabled) {
  219. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  220. UniWebViewInterface.SetLimitsNavigationsToAppBoundDomains(enabled);
  221. #endif
  222. }
  223. /// <summary>
  224. /// Clears any saved credentials for HTTP authentication for both Basic and Digest.
  225. ///
  226. /// On both iOS and Android, the user input credentials will be stored permanently across session.
  227. /// It could prevent your users to input username and password again until they changed. If you need the
  228. /// credentials only living in a shorter lifetime, call this method at proper timing.
  229. ///
  230. /// On iOS, it will clear the credentials immediately and completely from both disk and network cache.
  231. /// On Android, it only clears from disk database, the authentication might be still cached in the network stack
  232. /// and will not be removed until next session (app restarting).
  233. ///
  234. /// The client logout mechanism should be implemented by the Web site designer (such as server sending a HTTP
  235. /// 401 for invalidating credentials).
  236. ///
  237. /// </summary>
  238. /// <param name="host">The host to which the credentials apply. It should not contain any thing like scheme or path part.</param>
  239. /// <param name="realm">The realm to which the credentials apply.</param>
  240. public static void ClearHttpAuthUsernamePassword(string host, string realm) {
  241. UniWebViewInterface.ClearHttpAuthUsernamePassword(host, realm);
  242. }
  243. /// <summary>
  244. /// Sets whether a prompt alert should be displayed for collection username and password when the web view receives an
  245. /// HTTP authentication challenge (HTTP Basic or HTTP Digest) from server.
  246. ///
  247. /// By setting with `false`, no prompt will be shown and the user cannot login with input credentials. In this case,
  248. /// you can only access this page by providing username and password through the URL like: "http://username:password@example.com".
  249. /// If the username and password does not match, normally an error with 401 as status code would be returned (this behavior depends
  250. /// on the server implementation). If set with `true`, a prompt will be shown when there is no credentials provided or it is not
  251. /// correct in the URL.
  252. ///
  253. /// Default is `true`.
  254. /// </summary>
  255. /// <param name="flag">Whether a prompt alert should be shown for HTTP authentication challenge or not.</param>
  256. public void SetAllowHTTPAuthPopUpWindow(bool flag) {
  257. UniWebViewInterface.SetAllowHTTPAuthPopUpWindow(listener.Name, flag);
  258. }
  259. /// <summary>
  260. /// Adds the URL to download inspecting list.
  261. ///
  262. /// If a response is received in main frame and its URL is already in the inspecting list, a download task will be
  263. /// triggered. Check "Download Files" guide for more.
  264. ///
  265. /// This method only works on iOS and macOS Editor.
  266. /// </summary>
  267. /// <param name="urlString">The inspected URL.</param>
  268. /// <param name="type">The download matching type used to match the URL. Default is `ExactValue`.</param>
  269. public void AddDownloadURL(string urlString, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  270. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  271. UniWebViewInterface.AddDownloadURL(listener.Name, urlString, (int)type);
  272. #endif
  273. }
  274. /// <summary>
  275. /// Removes the URL from download inspecting list.
  276. ///
  277. /// If a response is received in main frame and its URL is already in the inspecting list, a download task will be
  278. /// triggered. Check "Download Files" guide for more.
  279. ///
  280. /// This method only works on iOS and macOS Editor.
  281. /// </summary>
  282. /// <param name="urlString">The inspected URL.</param>
  283. /// <param name="type">The download matching type used to match the URL. Default is `ExactValue`.</param>
  284. ///
  285. public void RemoveDownloadURL(string urlString, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  286. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  287. UniWebViewInterface.RemoveDownloadURL(listener.Name, urlString, (int)type);
  288. #endif
  289. }
  290. /// <summary>
  291. /// Adds the MIME type to download inspecting list.
  292. ///
  293. /// If a response is received in main frame and its MIME type is already in the inspecting list, a
  294. /// download task will be triggered. Check "Download Files" guide for more.
  295. ///
  296. /// This method only works on iOS and macOS Editor.
  297. /// </summary>
  298. /// <param name="MIMEType">The inspected MIME type of the response.</param>
  299. /// <param name="type">The download matching type used to match the MIME type. Default is `ExactValue`.</param>
  300. public void AddDownloadMIMEType(string MIMEType, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  301. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  302. UniWebViewInterface.AddDownloadMIMEType(listener.Name, MIMEType, (int)type);
  303. #endif
  304. }
  305. /// <summary>
  306. /// Removes the MIME type from download inspecting list.
  307. ///
  308. /// If a response is received in main frame and its MIME type is already in the inspecting list, a
  309. /// download task will be triggered. Check "Download Files" guide for more.
  310. ///
  311. /// This method only works on iOS and macOS Editor.
  312. /// </summary>
  313. /// <param name="MIMEType">The inspected MIME type of the response.</param>
  314. /// <param name="type">The download matching type used to match the MIME type. Default is `ExactValue`.</param>
  315. public void RemoveDownloadMIMETypes(string MIMEType, UniWebViewDownloadMatchingType type = UniWebViewDownloadMatchingType.ExactValue) {
  316. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  317. UniWebViewInterface.RemoveDownloadMIMETypes(listener.Name, MIMEType, (int)type);
  318. #endif
  319. }
  320. /// <summary>
  321. /// Sets whether allowing users to edit the file name before downloading. Default is `true`.
  322. ///
  323. /// If `true`, when a download task is triggered, a dialog will be shown to ask user to edit the file name and the
  324. /// user has a chance to choose if the they actually want to download the file. If `false`, the file download will
  325. /// start immediately without asking user to edit the file name. The file name is generated by guessing from the
  326. /// content disposition header and the MIME type. If the guessing of the file name fails, a random string will be
  327. /// used.
  328. ///
  329. /// </summary>
  330. /// <param name="allowed">
  331. /// Whether the user can edit the file name and determine whether actually starting the downloading.
  332. /// </param>
  333. public void SetAllowUserEditFileNameBeforeDownloading(bool allowed) {
  334. UniWebViewInterface.SetAllowUserEditFileNameBeforeDownloading(listener.Name, allowed);
  335. }
  336. /// <summary>
  337. /// Sets whether allowing users to choose the way to handle the downloaded file. Default is `true`.
  338. ///
  339. /// On iOS, the downloaded file will be stored in a temporary folder. Setting this to `true` will show a system
  340. /// default share sheet and give the user a chance to send and store the file to another location (such as the
  341. /// File app or iCloud).
  342. ///
  343. /// On macOS Editor, setting this to `true` will allow UniWebView to open the file in Finder.
  344. ///
  345. /// This method does not have any effect on Android. On Android, the file is downloaded to the Download folder.
  346. ///
  347. /// </summary>
  348. /// <param name="allowed">Whether the user can choose the way to handle the downloaded file.</param>
  349. public void SetAllowUserChooseActionAfterDownloading(bool allowed) {
  350. #if (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  351. UniWebViewInterface.SetAllowUserChooseActionAfterDownloading(listener.Name, allowed);
  352. #endif
  353. }
  354. /// <summary>
  355. /// Enables or disables the automatic download when the web view receives a response that cannot be rendered inline.
  356. ///
  357. /// When set to `false`, UniWebView stops starting a download task for non-renderable resources (such as attachments
  358. /// with an unsupported MIME type). On iOS and macOS Editor, downloads triggered by `AddDownloadURL` or
  359. /// `AddDownloadMIMEType` still work. On Android, this controls downloads started by the system download listener.
  360. /// Default is `true`.
  361. /// </summary>
  362. /// <param name="enabled">Whether UniWebView should automatically start downloading non-renderable resources.</param>
  363. public void SetAutoDownloadEnabled(bool enabled) {
  364. #if UNITY_ANDROID && !UNITY_EDITOR
  365. UniWebViewInterface.SetAutoDownloadEnabled(listener.Name, enabled);
  366. #elif (UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX || UNITY_IOS) && !UNITY_EDITOR_WIN && !UNITY_EDITOR_LINUX
  367. UniWebViewInterface.SetAutoDownloadEnabled(listener.Name, enabled);
  368. #endif
  369. }
  370. /// <summary>
  371. /// Sets whether the `OnFileDownloadStarted` and `OnFileDownloadFinished` events should be raised even for an image
  372. /// saving action triggered by the callout (context) menu on Android.
  373. ///
  374. /// By default, the image saving goes through a different route and it does not trigger the `OnFileDownloadStarted`
  375. /// and `OnFileDownloadFinished` events like other normal download tasks. Setting this with enabled with `true` if
  376. /// you also need to get notified when user long-presses on the image and taps "Save Image" button. By default, the
  377. /// image will be saved to the Downloads directory and you can get the path from the parameter
  378. /// of `OnFileDownloadFinished` event.
  379. ///
  380. /// This only works on Android. On iOS, there is no way to get a callback or any event from the "Add to Photos"
  381. /// button in the callout menu.
  382. /// </summary>
  383. /// <param name="enabled">Whether the context menu image saving action triggers the download related events.</param>
  384. public void SetDownloadEventForContextMenuEnabled(bool enabled) {
  385. #if UNITY_ANDROID && !UNITY_EDITOR
  386. UniWebViewInterface.SetDownloadEventForContextMenuEnabled(listener.Name, enabled);
  387. #endif
  388. }
  389. }