WebView2 allows hosting web content in Windows apps by creating separate environments for the browser's UI and the web content. This isolation ensures that user data for web content (tabs) is kept separate from the browser's own UI data.
To implement this, use CreateCoreWebView2EnvironmentWithOptions to create a content environment first, then create a separate UI environment using a different user data directory.
// 1. Create environment for web content (tabs)
std::wstring userDataDirectory = GetAppDataDirectory();
userDataDirectory.append(L"\User Data");
HRESULT hr = CreateCoreWebView2EnvironmentWithOptionsWithOptions(nullptr, userDataDirectory.c_str(),
L"", Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
[this](HRESULT result, ICoreWebView2Environment* env) -> HRESULT
{
m_contentEnv = env;
return InitUIWebViews();
}).Get());
// 2. Inside InitUIWebViews, create environment for browser UI
std::wstring browserDataDirectory = GetAppDataDirectory();
browserDataDirectory.append(L"\Browser Data");
return CreateCoreWebView2EnvironmentWithOptions(nullptr, browserDataDirectory.c_str(),
L"", Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
[this](HRESULT result, ICoreWebView2Environment* env) -> HRESULT
{
m_uiEnv = env;
// Create UI WebViews (controls, options, etc.)
return S_OK;
}).Get());