WinUI 3 中的 WebView2 (Windows App SDK) 應用程式

以下考量適用於 WinUI 3 (Windows App SDK) 應用程式中的 WebView2。

WinAppSDK 支援自訂 WebView2 環境

WinAppSDK 支援自訂的 WebView2 環境,從 WinAppSDK 1.5 (1.5.0-experimental2) 開始。 欲了解更多資訊,請參閱 WinUI3 WebView2 搭配自訂 CoreWebView2Environment。

要實例化自訂 WebView2 環境,你可以用以下) 列出的 (覆蓋 WebView2.EnsureCoreWebView2Async 之一初始化 WebView2,並傳遞你的自訂 CoreWebView2Environment (,以及可選的自訂 CoreWebView2ControllerOptions) :

public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment)
public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment, CoreWebView2ControllerOptions controllerOptions)

另請參閱下方 「停用 SmartScreen 導航」的範例程式碼。

API 參考:

停用 SmartScreen 導航

WebView2 會將應用程式中導向的 URL 傳送至 SmartScreen 服務,以確保客戶的安全。 如果你想停用這個導覽,請使用自訂 CoreWebView2Environment的 ,如下:

CoreWebView2EnvironmentOptions environmentOptions = new CoreWebView2EnvironmentOptions();
environmentOptions.AdditionalBrowserArguments = "--disable-features=msSmartScreenProtection";

string browserFolder = null; // Use null to get default browser folder
string userDataFolder = null; // Use null to get default user data folder
CoreWebView2Environment environment = await CoreWebView2Environment.CreateWithOptionsAsync(
    browserFolder, userDataFolder, environmentOptions);

// ...

this.WebView2.EnsureCoreWebView2Async(environment);

使用環境變數停用 SmartScreen

我們不再建議使用環境變數。 改用上述基於 API 的程式碼方法。

  • Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--disable-features=msSmartScreenProtection");

此環境變數必須在建立前 CoreWebView2 設定,當 WebView2.Source 屬性 初始設定或 WebView2.EnsureCoreWebView2Async 方法 初次呼叫時即會發生。

設定 DefaultBackgroundColor

在 WinUI 3 的 WebView2 中,該 DefaultBackgroundColor 設定存在於 WebView2 的 XAML 物件上。 例如:

public MainWindow()
{
    this.InitializeComponent();
    MyWebView.DefaultBackgroundColor = Colors.LightBlue;
}

透明度

WinUI 3 不支援透明背景。 請參閱 WebView2 透明背景支援嗎? ·第2992期。

另請參閱

microsoft-ui-xaml Repo > Issues

Windows 應用程式文件:

Windows App SDK 參考:

WebView2 參考資料:

Windows 安全性文件: