Search code examples
delphiwebviewtedgebrowser

TedgeBrowser how to give the option CoreWebView2EnvironmentOptions.Language


With Delphi 11.3, i use the webview2 via the tedgeBrowser component. The application using the Tedgebrowser is running on servers running an english Windows. By default the tedgebrowser has a navigator.language value to "en-US".

But i want to be able to change that value.

I found information about the property CoreWebView2EnvironmentOptions.Language But i don't see how to give that language property with the tedgebrowser component.

I also see that some of you recommend to use another component : Webview4Delphi. I tried with the Webview4Delphi demo "simplebrowser" to do this :

initialization

GlobalWebView2Loader := TWVLoader.Create(nil);
GlobalWebView2Loader.UserDataFolder := ExtractFileDir(Application.ExeName) +
  '\CustomCache';
GlobalWebView2Loader.Language := 'fr';  // here my test 
GlobalWebView2Loader.StartWebView2;

But it does no effect. When i do a alert(navigator.language) it still give the default language (OS language).

Can anyone help me with this ?


Solution given by Salvador helped me but was working partially in my case. I applied Salvador's solution + the way given by NoriyukiIchijo on that post :https://github.com/MicrosoftEdge/WebView2Feedback/issues/833#issuecomment-890281898


Solution

  • According to the documentation setting CoreWebView2EnvironmentOptions.Language should also change the Accept-language header but there's a low priority bug in WebView2 and this feature is not working at this moment.

    There's a workaround if you change the headers manually. You would have to set a filter in the TWVBRowser.OnAfterCreation event like this :

    procedure TMiniBrowserFrm.WVBrowser1AfterCreated(Sender: TObject);
    begin
      WVWindowParent1.UpdateSize;
      WVBrowser1.AddWebResourceRequestedFilter('*', COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL);
    end;
    

    The filter is needed to use the TWVBrowser.OnWebResourceRequested event to modify the HTTP headers like this :

    procedure TMiniBrowserFrm.WVBrowser1WebResourceRequested(Sender: TObject; const aWebView: ICoreWebView2; const aArgs: ICoreWebView2WebResourceRequestedEventArgs);
    var
      TempArgs : TCoreWebView2WebResourceRequestedEventArgs;
      TempRequestHeaders : ICoreWebView2HttpRequestHeaders;
    begin
      TempArgs:= TCoreWebView2WebResourceRequestedEventArgs.Create(aArgs);
      try
        TempArgs.Request.Get_Headers(TempRequestHeaders);
        TempRequestHeaders.SetHeader('Accept-Language','fr-fr');
      finally
        TempArgs.Free;
      end;
    end;
    

    Additionally, you would also have to set GlobalWebView2Loader.Language := 'fr-fr'; before the GlobalWebView2Loader.StartWebView2 call to change the user interface language.