Search code examples
delphivcltedgebrowser

How to set useragent in new Delphi TEdgeBrowser?


I need to change the user agent in the TEdgeBrowser

How to set useragent in new Delphi TEdgeBrowser VCL ?

Also any workarounds are welcome!


Solution

  • I found a solution.

    Microsoft has updated WebView2 and added the ability to change a user agent. But Embarcadero has not updated the component.

    Create new interface

    unit Webview2Ex;
    
    interface
    
    uses
        WebView2;
    
    const
       IID_ICoreWebView2Settings2: TGUID = '{EE9A0F68-F46C-4E32-AC23-EF8CAC224D2A}';
    
    type
    
      ICoreWebView2Settings2 = interface(ICoreWebView2Settings)
        ['{EE9A0F68-F46C-4E32-AC23-EF8CAC224D2A}']
        function Get_UserAgent(out UserAgent: PWideChar): HResult; stdcall;
        function Set_UserAgent(UserAgent: PWideChar): HResult; stdcall;
      end;
    
    implementation
    
    end.
    

    Create handler onCreateWebViewCompleted

     procedure TAiForm.RBrowserCreateWebViewCompleted(Sender: TCustomEdgeBrowser;
              AResult: HRESULT);
            var
                Ctrl2     : ICoreWebView2Settings2;
                HR        : HRESULT;
                UA        : PWideChar;
            begin
    //You must query SettingsInterface2 from SettingsInterface it's important
             Sender.SettingsInterface.QueryInterface(IID_ICoreWebView2Settings2, Ctrl2);
                if not Assigned(Ctrl2) then
                    raise Exception.Create('ICoreWebView2Settings2 not found');
            
                UA := 'NEW UA';
                HR := Ctrl2.Set_UserAgent(UA);
            
                HR := Ctrl2.Get_UserAgent(UA);
                if not SUCCEEDED(HR) then
                    raise Exception.Create('Get_UserAgent failed')
                    else ShowMessage(ua);
            end;
    

    Also need update WebView2 component from Microsoft

    https://developer.microsoft.com/en-us/microsoft-edge/webview2/

    If you want update all interfaces read this article

    WebView2 (TEdgeBrowser) updated Delphi interface (e.g. ICoreWebView2Controller2)