为来自 Delphi TWebBrowser 的 AJAX 调用更改用户代理

Change User-Agent for AJAX calls from Delphi TWebBrowser

我有一个 Delphi 应用程序可以在嵌入式网络浏览器中加载 Google 地图 JavaScript API。它加载的页面如下所示:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <style>
       #map {
        height: 400px;
        width: 100%;
       }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {});
      }
    </script>

    <script async defer
    src="https://maps.googleapis.com/maps/api/js?v=3.29&key=~APIKEY~&callback=initMap">
    </script>
  </body>
</html>

我正在 TWebBrowser:

中显示这样的页面
str := StringReplace(htmlBase, '~APIKEY~', cMapsAPIKey, []);

if not Assigned(WebBrowser.Document) then
  WebBrowser.Navigate('about:blank', '1', '', '', 'User-Agent: Mozilla/5.0');

doc := WebBrowser.Document;
doc.Clear;
doc.Write(str);
doc.Close;

TWebBrowser.Navigate() 将使用我为主页提供的用户代理字符串,但它使用它来加载脚本:

User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3)

从 3.29 开始,Google 地图 JavaScript API 似乎正在检查浏览器的用户代理并显示错误消息:"You are using a browser that is not supported"。这不是 3.28 或更低版本的问题。支持浏览器(使用 IE 11),只是发送了错误的用户代理字符串。

在 JavaScript 端,如何在不完全禁用警告的情况下覆盖用户代理检查?在 Delphi 端,有没有办法更改 AJAX 调用的用户代理?

编辑:覆盖 TWebBrowser.Invoke() 让我可以更改所有 HTTP 请求的用户代理,但看起来 navigator.userAgent 没有被更改。

您似乎正在使用 VCL 的 TWebBrowser. Per Changing the UA (User Agent) of a TWebBrowser component,您可以从 TWebBrowser 派生一个新的 class 以将其 Invoke() 方法覆盖到 return请求 DISPID_AMBIENT_USERAGENT 属性 时所需的 UserAgent 字符串。然后向浏览器查询其 IOleControl 接口并调用其 OnAmbientPropertyChange() 方法以向浏览器发出信号 DISPID_AMBIENT_USERAGENT 属性 值已更改。文章有完整代码。

为了更好的衡量,在 FMX 的 TWebBrowser, per Change User Agent for FireMonkey TWebBrowser, on Android you can use a helper class and RTTI trickery to access the browser's internal Java WebView object and call its WebSettings.setUserAgentString() method. Not sure about Windows, but on iOS you don't customize the user agent via the web browser itself (unless you hack the FMX framework to customize the requests it sends), you have to create a dictionary containing an item named UserAgent and register it with the global standardUserDefaults dictionary using its registerDefaults() 方法中。 Delphi 你是怎么做到的,我不知道。

您的 Google 地图网页无法在 TWebBrowser 组件中正常加载的问题是因为它在兼容模式下工作。这也是提到用户代理字符串的原因。

那么为什么会这样。嗯,TWebBrowser 只是 Internet Explorer 浏览器的包装器 API。根据 Microsoft 的决定,任何使用此类 API 的应用程序都将默认以兼容模式显示网页。

您可以使用此处的说明禁用此功能: