How to make a webview transparent?

By default, if a webpage doesn't specify a background, 3D WebView sets its background to white in order to match the behavior of typical web browsers. However, there are two approaches to disable the default white background so that a web page can be transparent:

Please also see the following sections for additional information:

Enabling transparency via HTML

A web page itself can opt into having a transparent background by including the following <meta> HTML tag inside its <head>

<meta name="transparent" content="true">

If a web page includes this meta tag and doesn't assign an opaque background via CSS, then its background will be transparent. For example, 3D WebView's keyboard UI is a React.js app that uses that tag to achieve a transparent background.

Enabling transparency via C#

Another option is that an application can disable the default white background for a webview using the IWebView.SetDefaultBackgroundEnabled() method, like this:

await webViewPrefab.WaitUntilInitialized();
// Disable the default white background so the page can be transparent.
webViewPrefab.WebView.SetDefaultBackgroundEnabled(false);

Limitations

Nearly all of the 3D WebView packages support transparent webviews, but there are two exceptions:

Alternatives

  • If you want to make an entire webview partially transparent, an alternative is to place a CanvasWebViewPrefab inside a CanvasGroup and then use the CanvasGroup.alpha setting to control transparency.

  • WebViewPrefab has an undocumented SetCutoutRect() method that enables it to turn black pixels into transparent pixels within a given rect, and the Keyboard component uses that method to make its background look transparent for Android Gecko and Hololens. Here's the code excerpt from BaseKeyboard.cs that uses SetCutoutRect():

    // Android Gecko and Hololens don't support transparent webviews, so set the cutout
    // rect to the entire view so that the shader makes its black background pixels transparent.
    if (pluginType == WebPluginType.AndroidGecko || pluginType == WebPluginType.UniversalWindowsPlatform) {
        _webViewPrefab.SetCutoutRect(new Rect(0, 0, 1, 1));
    }

Troubleshooting

If you've tried to enable a transparent background but the webview's background is still white, please check the following:

  • First, check the limitations section to verify that transparency is supported for your case.
  • Usually if a webview still has a white background after enabling transparency, it's because the web page has explicitly set a white background for an HTML element that spans the entire page (like the <html> or <body> elements), which prevents the page from being transparent. Please use remote debugging or your web browser's DevTools to check if that is the case and, if so, update the web page so that it no longer sets a background.