Wednesday, May 22, 2013

.NET: Get user agent string of the WebBrowser control using JavaScript

System::String^ GetUserAgent()
{
    System::String^ userAgent = System::String::Empty;

    try
    {
        System::String^ javascript =
            "<script type='text/javascript'>" +
            "function getUserAgent()" +
            "{document.write(navigator.userAgent)}" +
            "</script>";

        System::Windows::Forms::WebBrowser^ webBrowser =
            gcnew System::Windows::Forms::WebBrowser();
        webBrowser->Url = gcnew System::Uri( "about:blank" );
        webBrowser->Document->Write( javascript );
        webBrowser->Document->InvokeScript( "getUserAgent" );

        userAgent = webBrowser->DocumentText->Substring( javascript->Length );

        delete webBrowser;
        webBrowser = nullptr;
    }
    catch( ... )
    {
    }

    return userAgent;
}

No comments: