简体   繁体   English

更改WebBrowser控件的用户代理

[英]Changing the user agent of the WebBrowser control

I am trying to change the UserAgent of the WebBrowser control in a Winforms application. 我正在尝试在Winforms应用程序中更改WebBrowser控件的UserAgent。

I have successfully achieved this by using the following code: 我已经通过使用以下代码成功实现了这一目标:

[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
    int dwOption, string pBuffer, int dwBufferLength, int dwReserved);

const int URLMON_OPTION_USERAGENT = 0x10000001;

public void ChangeUserAgent()
{
    List<string> userAgent = new List<string>();
    string ua = "Googlebot/2.1 (+http://www.google.com/bot.html)";

    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, ua, ua.Length, 0);
}

The only problem is that this only works once. 唯一的问题是,这只能运行一次。 When I try to run the ChangeUserAgent() method for the second time it doesn't work. 当我第二次尝试运行ChangeUserAgent()方法时,它不起作用。 It stays set to the first changed value. 它保持设置为第一个更改的值。 This is quite annoying and I've tried everything but it just won't change more than once. 这是很烦人的事情,我已经尝试了所有方法,但变化不会超过一次。

Does anyone know of a different, more flexible approach? 有谁知道另一种更灵活的方法?

Thanks 谢谢

The easiest way: 最简单的方法:

webBrowser.Navigate("http://localhost/run.php", null, null,
                    "User-Agent: Here Put The User Agent");

I'm not sure whether I should just copy/paste from a website , but I'd rather leave the answer here, instead of a link. 我不确定是否应该从网站复制/粘贴,但我想在这里留下答案,而不是链接。 If anyone can clarify in comments, I'll be much obliged. 如果有人可以在评论中澄清,我将有义务。

Basically, you have to extend the WebBrowser class. 基本上,您必须扩展WebBrowser类。

public class ExtendedWebBrowser : WebBrowser
{
    bool renavigating = false;

    public string UserAgent { get; set; }

    public ExtendedWebBrowser()
    {
        DocumentCompleted += SetupBrowser;

        //this will cause SetupBrowser to run (we need a document object)
        Navigate("about:blank");
    }

    void SetupBrowser(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        DocumentCompleted -= SetupBrowser;
        SHDocVw.WebBrowser xBrowser = (SHDocVw.WebBrowser)ActiveXInstance;
        xBrowser.BeforeNavigate2 += BeforeNavigate;
        DocumentCompleted += PageLoaded;
    }

    void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

    }

    void BeforeNavigate(object pDisp, ref object url, ref object flags, ref object targetFrameName,
        ref object postData, ref object headers, ref bool cancel)
    {
        if (!string.IsNullOrEmpty(UserAgent))
        {
            if (!renavigating)
            {
                headers += string.Format("User-Agent: {0}\r\n", UserAgent);
                renavigating = true;
                cancel = true;
                Navigate((string)url, (string)targetFrameName, (byte[])postData, (string)headers);
            }
            else
            {
                renavigating = false;
            }
        }
    }
}

Note: To use the method above you'll need to add a COM reference to “Microsoft Internet Controls”. 注意:要使用上述方法,您需要将COM引用添加到“ Microsoft Internet控件”。

He mentions your approach too, and states that the WebBrowser control seems to cache this user agent string, so it will not change the user agent without restarting the process. 他也提到了您的方法,并指出WebBrowser控件似乎在缓存此用户代理字符串,因此,如果不重新启动该进程,它将不会更改用户代理。

Also, there is a refresh option in the function (according to MSDN ). 另外,该函数中有一个刷新选项(根据MSDN )。 It worked well for me (you should set it before any user agent change). 它对我来说效果很好(您应该在更改任何用户代理之前进行设置)。 Then the question code could be changed like this: 然后可以这样更改问题代码:

[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
    int dwOption, string pBuffer, int dwBufferLength, int dwReserved);

const int URLMON_OPTION_USERAGENT = 0x10000001;
const int URLMON_OPTION_USERAGENT_REFRESH = 0x10000002;

public void ChangeUserAgent()
{
    string ua = "Googlebot/2.1 (+http://www.google.com/bot.html)";

    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT_REFRESH, null, 0, 0);
    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, ua, ua.Length, 0);
}

I'd like to add to @Jean Azzopardi's answer. 我想补充@Jean Azzopardi的答案。

void BeforeNavigate(object pDisp, ref object url, ref object flags, ref object targetFrameName,
        ref object postData, ref object headers, ref bool cancel)
{
    // This alone is sufficient, because headers is a "Ref" parameters, and the browser seems to pick this back up.
    headers += string.Format("User-Agent: {0}\r\n", UserAgent);
}

This solution worked best for me. 此解决方案最适合我。 Using the renavigating caused other weird issues for me, like the browser content suddenly vanishing, and sometimes still getting Unsupported Browser. 使用重新导航给我造成了其他奇怪的问题,例如浏览器内容突然消失,有时仍然会出现Unsupported Browser。 With this technique, all the requests in Fiddler had the correct User Agent. 使用这种技术,Fiddler中的所有请求都具有正确的用户代理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM