0

I need to obtain current (or default) User Agent string of the WebBrowser WinForms control (.net 2 or 3.5).

I found how to change it to my own string ( Changing the user agent of the WebBrowser control ) but I prefer to use default one.

In short, I use WebBrowser to allow user to login a site. Then I take session cookies and use it for my JSON HttpWebRequest and wish to use same user agent to prevent problems.

Community
  • 1
  • 1
G-Shadow
  • 188
  • 3
  • 13

1 Answers1

2

You can insert some javascript which gets the useragent and passes it back to the WinForms application.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigated += webBrowser1_Navigated;
        webBrowser1.Navigate("www.google.com");
    }

    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        var scriptingObject = new UserAgentScriptingObject();
        webBrowser1.ObjectForScripting = scriptingObject;

        HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
        scriptEl.SetAttribute("text", "function myscript() { window.external.SetUserAgent(navigator.userAgent); }");
        webBrowser1.Document.GetElementsByTagName("head")[0].AppendChild(scriptEl);
        webBrowser1.Document.InvokeScript("myscript");
    }
}

[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class UserAgentScriptingObject
{
    public void SetUserAgent(string userAgent)
    {
        MessageBox.Show(userAgent);
    }
}
Bruno
  • 1,213
  • 13
  • 14
  • Thanks, this works! The only thing, I had to use "scriptEl.SetAttribute("text", "... script here ..."), because attempt to write InnerText causes exception (forbidden to write it for scripts probably) - solution from here: http://stackoverflow.com/a/6222430 – G-Shadow Feb 24 '16 at 11:02
  • Glad I could help. I adjusted the code with the SetAttribute call. – Bruno Feb 24 '16 at 12:59