CefSharp 3 set proxy at Runtime
Asked Answered
R

5

6

I downloaded CEF (chromuim embedded framework) binary distributation that comes with (cefclient & cefsimple) c++ examples, And Realized that cefclient can change proxy settings on run-time.

And the key to do that is to Grab the RequestContext and call the function SetPreference.

on CefClient all works just nice.

but on CefSharp calling SetPreference always returns false, and also HasPreference returns false for the preference name "proxy".

Rozalin answered 18/3, 2016 at 22:53 Comment(2)
Jump on Gitter, read over the conversation from yesterday, you all the details you need. Likely your calling on the incorrect thread, there's only one thread that will work. gitter.im/cefsharp/CefSharpInexact
thanks a lot , a was wondering how to get to run the code on the proper thread, but I was distracted with code defferences between c++ and c# wrappers.Rozalin
R
8

thanks to amaitland the proper way to actively inforce changing the request-context prefrences, is to run the code on CEF UIThread as following:

    Cef.UIThreadTaskFactory.StartNew(delegate {
        var rc = this.browser.GetBrowser().GetHost().RequestContext;
        var v = new Dictionary<string, object>();
        v["mode"] = "fixed_servers";
        v["server"] = "scheme://host:port";
        string error;
        bool success = rc.SetPreference("proxy", v, out error);
        //success=true,error=""
    });
Rozalin answered 19/3, 2016 at 20:51 Comment(3)
I am getting "trying to modify a reference that is not user modifiable"Rayraya
@Inexact can you please describe where and how the above ? I want to change proxy at runtime after Cef.Initialized so please let me know . Thank youCoolidge
I tried the above but nothing happens it is still using my default ip , Any suggestions ?Coolidge
M
4

if anyone need any other soulition i found this solution.

Cef.UIThreadTaskFactory.StartNew(delegate
        {
            string ip = "ip or adress";
            string port = "port";
            var rc = this.browser.GetBrowser().GetHost().RequestContext;
            var dict = new Dictionary<string, object>();
            dict.Add("mode", "fixed_servers");
            dict.Add("server", "" + ip + ":" + port + "");
            string error;
            bool success = rc.SetPreference("proxy", dict, out error);

        });
Maggiemaggio answered 26/5, 2016 at 12:50 Comment(0)
S
3

I downloaded CefSharp.WinForms 65.0.0 and made class, that can help to start working with proxy:

public class ChromeTest
{
    public static ChromiumWebBrowser Create(WebProxy proxy = null, Action<ChromiumWebBrowser> onInited = null)
    {
       var result = default(ChromiumWebBrowser);
        var settings = new CefSettings();
        result = new ChromiumWebBrowser("about:blank");
        if (proxy != null)
            result.RequestHandler = new _requestHandler(proxy?.Credentials as NetworkCredential);

        result.IsBrowserInitializedChanged += (s, e) =>
        {
            if (!e.IsBrowserInitialized)
                return;

            var br = (ChromiumWebBrowser)s;
            if (proxy != null)
            {
                var v = new Dictionary<string, object>
                {
                    ["mode"] = "fixed_servers",
                    ["server"] = $"{proxy.Address.Scheme}://{proxy.Address.Host}:{proxy.Address.Port}"
                };
                if (!br.GetBrowser().GetHost().RequestContext.SetPreference("proxy", v, out string error))
                    MessageBox.Show(error);
            }

            onInited?.Invoke(br);
        };

        return result;
    }

    private class _requestHandler : DefaultRequestHandler
    {
        private NetworkCredential _credential;

        public _requestHandler(NetworkCredential credential = null) : base()
        {
            _credential = credential;
        }

        public override bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
        {
            if (isProxy == true)
            {
                if (_credential == null)
                    throw new NullReferenceException("credential is null");

                callback.Continue(_credential.UserName, _credential.Password);
                return true;
            }

            return false;
        }
    }
}

Using:

        var p = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
        var p1 = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));
        var p2 = new WebProxy("Scheme://Host:Port", true, new[] { "" }, new NetworkCredential("login", "pass"));

        wb1 = ChromeTest.Create(p1, b => b.Load("http://speed-tester.info/check_ip.php"));
        groupBox1.Controls.Add(wb1);
        wb1.Dock = DockStyle.Fill;

        wb2 = ChromeTest.Create(p2, b => b.Load("http://speed-tester.info/check_ip.php"));
        groupBox2.Controls.Add(wb2);
        wb2.Dock = DockStyle.Fill;

        wb3 = ChromeTest.Create(p, b => b.Load("http://speed-tester.info/check_ip.php"));
        groupBox3.Controls.Add(wb3);
        wb3.Dock = DockStyle.Fill;
Scala answered 7/8, 2018 at 9:59 Comment(7)
Whats the locking for? Nothing you are doing should require locking. Whats the string visitor for? IsBrowserInitializedChanged Should already be called on the cef ui thread, no need to create a task. Keep a reference to the RequestContext you create and simplify your code You should also include what version of CefSharp you are using.Inexact
Please improve the description of your source code. Otherwise, this post does not seem to provide a quality answer to the question. Please either edit your answer, or just post it as a comment to the question.Flak
Thank's @Inexact and sorry, I did not completely clean up the code from the working solution and left some pieces. I've edited code according your comments.Scala
@amaitland, now expression rc.SetPreference("proxy", v, out string error) throwing System.NullReferenceException, I checked rc.Equals(br.GetBrowser().GetHost().RequestContext) and got false. I expected that rc is just reference to current RequestContext. Is it normal behaviour?Scala
Without a stacktrace I cannot really say.Inexact
Just go back to what you had for now.Inexact
@amaitland, thank you for your feedback, i'm edited code, it's working now.Scala
S
1

If you want dynamic proxy resolver (proxy hanlder), which allow you to use different proxy for different host - you should:

1) Prepare javascript

var proxy1Str = "PROXY 1.2.3.4:5678";
var proxy2Str = "PROXY 2.3.4.5:6789";

var ProxyPacScript = 
    $"var proxy1 = \"{(proxy1Str.IsNullOrEmpty() ? "DIRECT" : proxy1Str)}\";" +
    $"var proxy2 = \"{(proxy2Str.IsNullOrEmpty() ? "DIRECT" : proxy2Str)}\";" +

    @"function FindProxyForURL(url, host) {
        if (shExpMatch(host, ""*example.com"")) {
            return proxy1;
        }
        return proxy2;
    }";

var bytes = Encoding.UTF8.GetBytes(ProxyPacScript);
var base64 = Convert.ToBase64String(bytes);

2) Set it correctly

var v = new Dictionary<string, object>();
v["mode"] = "pac_script";
v["pac_url"] = "data:application/x-ns-proxy-autoconfig;base64," + base64;

3) Call SetPreference as in accepted answer https://mcmap.net/q/1611991/-cefsharp-3-set-proxy-at-runtime

As result all request to *example.com will flow throught proxy1, all others through proxy2.

To do it I spent all day but with help of source (https://cs.chromium.org/) I found solution. Hope it helps someone.

Main problems:

1) In new version (72 or 74 as I remember) there is no ability to use "file://..." as pac_url.

2) We can't use https://developer.chrome.com/extensions/proxy in cef.. or i can't find how to do it.

p.s. How to use another types of proxy (https, socks) - https://chromium.googlesource.com/chromium/src/+/master/net/docs/proxy.md#evaluating-proxy-lists-proxy-fallback

Sandoval answered 2/10, 2019 at 15:41 Comment(4)
Example looks incomplete, you build the package url, doesn't actually call SetPreference, best to show a complete example.Inexact
Forgot it. Thanks. Add step #3.Sandoval
Hi @СергейРыбаков where did you find the "pac_script" mode? Is there a place where I can see a list of possible modes?Natiha
@Natiha I'am sorry, I don't know where to find all values. May be in source?Sandoval
P
0

With the new version of CefSharp, it's quite simple to set proxy:

browser = new ChromiumWebBrowser();
panel1.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
await browser.LoadUrlAsync("about:blank");
await Cef.UIThreadTaskFactory.StartNew(() =>
{
    browser.GetBrowser().GetHost().RequestContext.SetProxy("127.0.0.1", 1088, out string _);
});
Primate answered 28/7, 2022 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.