UserAgent.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Runtime.InteropServices;
  3. using System.Text.RegularExpressions;
  4. using UnityEngine;
  5. namespace ZenFulcrum.EmbeddedBrowser {
  6. /**
  7. * Cooks up the user agent to use for the browser.
  8. *
  9. * Ideally, we'd just say a little bit and let websites feature-detect, but many websites (sadly)
  10. * still use UA sniffing to decide what version of the page to give us.
  11. *
  12. * Notably, **Google** does this (for example, maps.google.com), which I find rather strange considering
  13. * that I'd expect them to be among those telling us to feature-detect.
  14. *
  15. * So, use this class to generate a pile of turd that looks like every other browser out there acting like
  16. * every browser that came before it so we get the "real" version of pages when we browse.
  17. */
  18. public class UserAgent {
  19. private static string agentOverride;
  20. /**
  21. * Returns a user agent that, hopefully, tricks legacy, stupid, non-feature-detection websites
  22. * into giving us their actual content.
  23. *
  24. * If you change this, the Editor will usually need to be restarted for changes to take effect.
  25. */
  26. public static string GetUserAgent() {
  27. if (agentOverride != null) return agentOverride;
  28. var chromeVersion = Marshal.PtrToStringAnsi(BrowserNative.zfb_getVersion());
  29. //(Note: I don't care what version of the OS you have, we're telling the website you have this
  30. //version so you get a good site.)
  31. string osStr = "Windows NT 6.1";
  32. #if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
  33. osStr = "Macintosh; Intel Mac OS X 10_7_0";
  34. #elif UNITY_EDITOR_LINUX || UNITY_STANDALONE_LINUX
  35. osStr = "X11; Linux x86_64";
  36. #endif
  37. var userAgent =
  38. "Mozilla/5.0 " +
  39. "(" + osStr + "; Unity 3D; ZFBrowser 2.0.0; " + Application.productName + " " + Application.version + ") " +
  40. "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" + chromeVersion + " Safari/537.36"
  41. ;
  42. //Chromium has issues with non-ASCII user agents.
  43. userAgent = Regex.Replace(userAgent, @"[^\u0020-\u007E]", "?");
  44. return userAgent;
  45. }
  46. public static void SetUserAgent(string userAgent) {
  47. if (BrowserNative.NativeLoaded) {
  48. throw new InvalidOperationException("User Agent can only be changed before native backend is initialized.");
  49. }
  50. agentOverride = userAgent;
  51. }
  52. }
  53. }