开发者

Selenium-rc: is there a way to change the user-agent without changing the Firefox profile

I want to run tests that change t开发者_StackOverflow社区he user-agent in the http request sent from the browser (like the FF add-on, user agent switcher does). I saw you can do it by playing with the FF profile (http://seleniumhq.org/docs/09_webdriver.html).

Is there a way to do it within a test? Something like the function addCustomRequestHeader() that sets a header rather than adding it


You could insert a function like this to change the user agent on the fly before you make your http request:

function changeuserAgent() {

    var altuserAgentGetter = function () {
        return "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2) Gecko/20100115 <choose your string>";
    };

    if (Object.defineProperty) {
        Object.defineProperty(navigator, "userAgent", {
            get: altuserAgentGetter
        });
    }
    else if (Object.prototype.__defineGetter__) {
        navigator.__defineGetter__("userAgent", altuserAgentGetter);
    } 
}


If you're using the Selenium 2 Web Driver in Java, you can create a Firefox profile and set the agent string as a preference in the profile. Then use the profile to create the WebDriver object:

    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("general.useragent.override", "Mozilla/5.0 (iPad; U; CPU OS 4_3 like Mac OS X; de-de) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F191 Safari/6533.18.5");
    WebDriver driver = new FirefoxDriver(profile);

For slightly more information and source code examples, see the Selenium Web Driver documentation for Firefox Driver at http://seleniumhq.org/docs/03_webdriver.html#firefox-driver.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜