Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BlazorWebView/WebView2 Transparent background not transparent on Windows #14185

Closed
StonedHackerman opened this issue Mar 24, 2023 · 18 comments
Closed
Labels
area-blazor Blazor Hybrid / Desktop, BlazorWebView external platform/windows 🪟 s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working

Comments

@StonedHackerman
Copy link

Description

What I did

I created a project from the default template ".NET MAUI Blazor App". In the MainPage I created a Label and a BlazorWebView which I shifted up a bit, so that it partly convers the Label. Then, I did these steps to make sure the page displayed in the BlazorWebView has transparent background:

  • Set the page's body background-color to transparent with CSS
html, body {
    background-color: transparent;
}
  • Set the BlazorWebView's backgroud color to transparent
<BlazorWebView x:Name="BlazorWebView" HostPage="wwwroot/index.html" BackgroundColor="Transparent" Margin="0,-10,0,0" MinimumHeightRequest="20">
  • Explicitly set the internal WebView2's DefaultBackgroundColor to transparent in an OnLoaded event handler
private void MainPage_OnLoaded(object sender, EventArgs e)
    {
        #if WINDOWS
        
        var webView = (BlazorWebView.Handler.PlatformView as Microsoft.UI.Xaml.Controls.WebView2);

        webView.DefaultBackgroundColor = Windows.UI.Color.FromArgb(0, 0, 0, 0);

        #endif
    }
  • Displayed a Razor page directly, containing only a single P element, to make sure no other HTML elements are blocking the transparency

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pages="clr-namespace:TransparencyTest.Pages"
             x:Class="TransparencyTest.MainPage"
             BackgroundColor="{DynamicResource PageBackgroundColor}"
             Loaded="MainPage_OnLoaded">

    <StackLayout>
        <Label>This is a MAUI label</Label>

        <BlazorWebView x:Name="BlazorWebView" HostPage="wwwroot/index.html" BackgroundColor="Transparent" 
                       Margin="0,-10,0,0" MinimumHeightRequest="20">
            <BlazorWebView.RootComponents>
                <RootComponent Selector="#app" ComponentType="{x:Type pages:Index}" />
            </BlazorWebView.RootComponents>
        </BlazorWebView>
    </StackLayout>

</ContentPage>

Index.razor

@page "/"

<p style="margin: 0">This is a P from Blazor</p>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
    <title>TransparencyTest</title>
    <base href="/" />

    <link href="css/app.css" rel="stylesheet" />
    <link href="TransparencyTest.styles.css" rel="stylesheet" />
</head>

<body>

    <div class="status-bar-safe-area"></div>

    <div id="app">Loading...</div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="" class="reload">Reload</a>
        <a class="dismiss">🗙</a>
    </div>

    <script src="_framework/blazor.webview.js" autostart="false"></script>

</body>

</html>

Result on Android (correct expected behavior)

On Android, I can correctly see the text in the P element on the Razor page inside a BlazorWebView overlayed on top of the MAUI Label

Screenshot 2023-03-24 14 54 27

Result on Windows (incorrect behavior)

On Windows, the background is not transparent

Screenshot 2023-03-24 14 52 56

The color displayed must be somehow related to the current Windows theme, because when I change my Windows theme from Dark to Light, the BlazorWebView's background color changes too

Screenshot 2023-03-24 15 22 49

According to this link to Microsoft's official documentation, setting a WebView2's DefaultBackgroundColor to transparent is supported:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2controller.defaultbackgroundcolor?view=webview2-dotnet-1.0.864.35#microsoft-web-webview2-core-corewebview2controller-defaultbackgroundcolor

Which leads a logical conclusion that this is a bug, and the background should be transparent, like on Android.

Platforms/versions

I'm using VS Community 2022 v17.5.3 and the latest MAUI workload

The project contains these TargetFrameworks: (just the defaults from the template)

<TargetFrameworks>net7.0-android;net7.0-ios;net7.0-maccatalyst</TargetFrameworks>
<TargetFrameworks Condition="$([MSBuild]::IsOSPlatform('windows'))">$(TargetFrameworks);net7.0-windows10.0.19041.0</TargetFrameworks>
        

This is the output from dotnet workload list

Installed Workload Id      Manifest Version       Installation Source
---------------------------------------------------------------------
maui-windows               7.0.59/7.0.100         VS 17.5.33516.290
maui-maccatalyst           7.0.59/7.0.100         VS 17.5.33516.290
maccatalyst                16.2.1024/7.0.100      VS 17.5.33516.290
maui-ios                   7.0.59/7.0.100         VS 17.5.33516.290
android                    33.0.26/7.0.100        VS 17.5.33516.290
ios                        16.2.1024/7.0.100      VS 17.5.33516.290
wasm-tools                 7.0.4/7.0.100          VS 17.5.33516.290
maui-android               7.0.59/7.0.100         VS 17.5.33516.290

Steps to Reproduce

  1. Download the code from the example repo
  2. Run on Windows
  3. See bug

Link to public reproduction project repository

https://github.com/StonedHackerman/MauiBlazorWebViewTransparencyTest/tree/main/TransparencyTest

Version with bug

7.0 (current)

Last version that worked well

Unknown/Other

Affected platforms

Windows

Affected platform versions

net7.0-windows10.0.19041.0

Did you find any workaround?

No, nothing I tried worked and no amount of Googling helped

Relevant log output

No response

@StonedHackerman StonedHackerman added the t/bug Something isn't working label Mar 24, 2023
@Eilon Eilon added the area-blazor Blazor Hybrid / Desktop, BlazorWebView label Mar 24, 2023
@Eilon
Copy link
Member

Eilon commented Mar 24, 2023

This might be a limitation of the WebView2 control on WinUI, which is what .NET MAUI uses on Windows. We'll have to check.

@StonedHackerman
Copy link
Author

It also seems to work under WPF (which also uses the same WebView2 no?), e.g. as this StackOverflow post shows:
https://stackoverflow.com/questions/67838739/how-to-use-transparency-in-webview2

@Eilon
Copy link
Member

Eilon commented Mar 24, 2023

Indeed, I recall the WPF issue, so I wonder if the same type of issue exists on WinUI as well. I found this issue, which seems to indicate that others have the same issue on WinUI: microsoft/microsoft-ui-xaml#6527

@Eilon
Copy link
Member

Eilon commented Mar 24, 2023

The other issue suggests that there could be a fairly easy workaround: microsoft/microsoft-ui-xaml#6527 (comment)

So you could easily try that in an #if WINDOWS section in your app's MauiProgram.cs.

@StonedHackerman
Copy link
Author

I inserted these lines in MauiProgram.cs at the beginning of the CreateMauiApp() method

#if WINDOWS

Environment.SetEnvironmentVariable("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", "0");

#endif

But the result is still the same. I also tried inserting this in the constructor of MainPage and the constructor of App in Platforms/Widows/App.xaml.cs but nothing ever changed

@Eilon
Copy link
Member

Eilon commented Mar 24, 2023

Hmm then possibly the workaround just doesn't work? Because that's otherwise the same as what the others were saying in the WebView2 thread.

@StonedHackerman
Copy link
Author

StonedHackerman commented Mar 24, 2023

At least on my machine ™ it doesn't. Edit: tried on another machine, doesnt work either

@Eilon
Copy link
Member

Eilon commented Mar 24, 2023

Hmm yeah I don't see it working either in my test.

@danroth27 danroth27 added this to the Backlog milestone Mar 27, 2023
@ghost
Copy link

ghost commented Mar 27, 2023

We've added this issue to our backlog, and we will work to address it as time and resources allow. If you have any additional information or questions about this issue, please leave a comment. For additional info about issue management, please read our Triage Process.

@jinxinjuan jinxinjuan added s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage labels Jun 16, 2023
@jinxinjuan
Copy link
Collaborator

Verified this issue with Visual Studio Enterprise 17.7.0 Preview 1.0. Can repro on windows platform with sample project. https://github.com/StonedHackerman/MauiBlazorWebViewTransparencyTest/tree/main/TransparencyTest.

@mhrastegari
Copy link

mhrastegari commented Aug 21, 2023

So how's the new Outlook doing it? it's web based too.
Screenshot (20)

@Eilon
Copy link
Member

Eilon commented Aug 24, 2023

So how's the new Outlook doing it? it's web based too.

I'm not sure how they do it, but I thought the whole app (except maybe the title bar?) was a WebView, so maybe they don't even need to use transparency? Or also, perhaps it's hosted natively, which has somewhat different behaviors compared to how it's hosted on WindowsAppSDK (WinUI) and WPF/WinForms.

@SimenCTan
Copy link

Have there been any updates regarding this issue

@SimenCTan
Copy link

to resolve the issue on macOS

  public static void ModifyBlazorWebView() 
  {
      ViewHandler.ViewMapper.AppendToMapping(nameof(IView.Background), (handler, view) =>
      {
#if MACCATALYST || IOS
          if (handler.PlatformView is WKWebView wv)
          {
              wv.Opaque = false;
              wv.BackgroundColor = UIColor.Clear;
          }
#endif
      });
  }

@Eilon Eilon removed this from the Backlog milestone Dec 15, 2023
@everharder
Copy link

Any news on this?

@shyqrirama
Copy link

This Solution seems to work, create a new control that inherits the base class BlazorWebView, and then based on platform(when on windows) add init event. Add the below code and the issue seems to go away.

private async void BlazorWebView_BlazorWebViewInitialized(object? sender, Microsoft.AspNetCore.Components.WebView.BlazorWebViewInitializedEventArgs e)
{
e.WebView.DefaultBackgroundColor = Windows.UI.Color.FromArgb(0, 255, 255, 255);
await e.WebView.EnsureCoreWebView2Async();
}

@everharder
Copy link

@shyqrirama Unfortanetly the solution doesn't work for me.
In the screenshot, the expected background color for the embedded website is blue (because that's the background color of the MainPage).

issue

Can you maybe provide a minimal working example of your solution?

@mkArtakMSFT
Copy link
Member

Closing as this is not something we control: microsoft/microsoft-ui-xaml#6527

@mkArtakMSFT mkArtakMSFT closed this as not planned Won't fix, can't repro, duplicate, stale Apr 5, 2024
@github-actions github-actions bot locked and limited conversation to collaborators May 6, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
area-blazor Blazor Hybrid / Desktop, BlazorWebView external platform/windows 🪟 s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working
Projects
None yet
Development

No branches or pull requests

10 participants