支援單一使用者資料檔案夾下的多個設定檔

WebView2 多重設定檔 API 可讓您建立及操作使用者設定檔,以使用 WebView2 控制項。 WebView2 中的設定檔在概念上類似于 Microsoft Edge 中的設定檔。 多個設定檔支援可讓 WebView2 應用程式在單一使用者資料檔案夾下擁有多個設定檔。

每個設定檔都有專用的設定檔資料夾來儲存瀏覽器資料,可為每個使用者提供個別的流覽資料儲存體,例如 Cookie、使用者喜好設定和快取資源。 與相同使用者設定檔相關聯的所有 WebView2 控制項都會共用單一設定檔資料夾。

先前的方法:針對每個 WebView2 控制項使用不同的使用者資料檔案夾

先前,若沒有多重設定檔支援,WebView2 應用程式可以針對不同的 WebView2 控制項使用不同的使用者資料檔案夾, 不過,在該方法中,您必須執行多個 WebView2 執行時間實例 (每個實例,包括瀏覽器進程和一堆子進程) ,這會耗用更多系統資源,包括記憶體、CPU 使用量和磁碟空間。

建立 WebView2 時指定設定檔

建立定義設定檔的 options 物件

上的 CreateCoreWebView2ControllerOptionsCoreWebView2Environment 方法會建立 options 物件 CoreWebView2ControllerOptions ,以提供設定檔的特定資訊,包括 ProfileNameIsInPrivateModeEnabled 。 建立 WebView2 控制項實例時,請使用這個物件來指定目標設定檔。

建立使用設定檔的 WebView2 控制項

每個 Create...Controller 接受 options 參數的方法都會建立 WebView2 控制項,並將它與您指定的設定檔產生關聯。 如果指定的設定檔不存在,將會建立新的設定檔。

建立 WebView2 時指定設定檔的範例

public async void CreateWebView2Controller(object sender, RoutedEventArgs e)
{
    var hwnd = new HwndForWV2();
    Window window = new Window();
    window.Content = hwnd;
    window.Show();

    var env = await CoreWebView2Environment.CreateAsync();
    var options = env.CreateCoreWebView2ControllerOptions();
    options.ProfileName = "MyProfile";
    options.IsInPrivateModeEnabled = true;
    var controller = await env.CreateCoreWebView2ControllerAsync(hwnd.Handle, options);

    controller.Bounds = new System.Drawing.Rectangle(0, 0, 800, 600);
    controller.CoreWebView2.Navigate("https://www.bing.com/");
    controller.CoreWebView2.NavigationStarting += CoreWebView_NavigationStarting;
}

存取和操作設定檔

您可以存取 Profile WebView2 控制項的 屬性來取得設定檔物件。

取得設定檔物件之後,您可以操作它。 使用 CoreWebView2Profile 取得設定檔資訊,並執行整個設定檔的設定和作業。

存取和操作設定檔的範例

string profileName = controller.CoreWebView2.Profile.ProfileName;
bool inPrivate = controller.CoreWebView2.Profile.IsInPrivateModeEnabled;

// update window title with profileName
UpdateAppTitle(profileName);

// update window icon
SetAppIcon(inPrivate);

另請參閱