'WebView2 proxy C++

I found this thread on GitHub, but seems that the code is not C++:

WebView2 _webView2 = new WebView2();

CoreWebView2EnvironmentOptions options = new CoreWebView2EnvironmentOptions();

// Set a proxy pac for the browser   
//      options.AdditionalBrowserArguments = "--proxy-pac-url=http://myproxy.com/my.pac";

// Set the proxy for the browser
options.AdditionalBrowserArguments = "--proxy-server=\"foopy:99\"";

// Create the environment manually
CoreWebView2Environment env = await CoreWebView2Environment.CreateAsync(null, null, options);
await _webView2 .EnsureCoreWebView2Async(env);

So the only what am I asking for is to provide the solution for setting up a proxy for WebView2 via C++.


I have ICoreWebView2 interface, but it doesn’t have EnsureCoreWebView2Async method. In another hand, I have CoreWebView2EnvironmentOptions class.



Solution 1:[1]

auto opt = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();

opt->put_AdditionalBrowserArguments(L"--proxy-server=\"SERVER\"");

CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, opt.Get(), Microsoft::WRL::Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
[hwnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {

...

}).Get());

Instead of SERVER put ip address or something else.


I tested, it works, but seems there is a bug (or feature): you can’t create two or more webviews with different run-arguments.

Solution 2:[2]

To those looking to specify webview environment options and cannot find CoreWebView2EnvironmentOptions in C++ similar to what is available in .Net. Visit documentation page for ICoreWebView2EnvironmentOptions and you should find this line:

A default implementation is provided in WebView2EnvironmentOptions.h

Include WebView2EnvironmentOptions.h and create CoreWebView2EnvironmentOptions as below

#include <WebView2EnvironmentOptions.h>

auto options = Microsoft::WRL::Make<CoreWebView2EnvironmentOptions>();
// Use options however you want. I simply added an argument to autoplay videos.
options->put_AdditionalBrowserArguments(L"--autoplay-policy=no-user-gesture-required");

HRESULT hr = CreateCoreWebView2EnvironmentWithOptions(
        subFolder, m_userDataFolder.c_str(), options.Get(),
        Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
            this, &AppWindow::OnCreateEnvironmentCompleted)
            .Get());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Okumaima
Solution 2 Monu Yadav