通过selenium设置userAgent是抛出异常

时间:2013-04-04 15:51:16

标签: selenium selenium-webdriver

我最近将我的硒从2.19.0更新到2.31.0。我在设置userAgent以进行测试时遇到问题。这是代码:

void testMessage() {
    verifySomething(this.driver, "iPhone");
}

void verifySomething(WebDriver driver, String userAgent) {
    String script = null;
    if (driver instanceof HtmlUnitDriver) {
        script = "navigator.userAgent=" + "'" + userAgent + "';";
    }
    else {
        // something
    }
    ((JavascriptExecutor) driver).executeScript(script);
}

我收到以下错误:

  

======= EXCEPTION START ========

EcmaError: lineNumber=[1] column=[0] lineSource=[] name=[TypeError] sourceName=[injected script] message=[TypeError: Cannot set property [Navigator].userAgent that has only a getter to iPhone. (injected script#1)]
com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot set property [Navigator].userAgent that has only a getter to iPhone. (injected script#1)
at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:663)
                at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:559)
                at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:525)
                at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:594)
                at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:569)
                at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:996)
                at org.openqa.selenium.htmlunit.HtmlUnitDriver.executeScript(HtmlUnitDriver.java:466)
...
...

==打电话给JAVASCRIPT ==

  function () {
      navigator.userAgent = "iPhone";
  }

======= EXCEPTION END ======== 

我知道它正在抱怨这个二传手。它用于在selenium 2.19.0中工作,但我猜他们可能已将该属性更改为只读。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

您无法在navigator.userAgent中设置任何内容。

navigator.UserAgent只是关于您当前浏览器的信息。

http://www.w3schools.com/jsref/prop_nav_useragent.asp

答案 1 :(得分:0)

对于FF使用此(profile.setPreference(“general.useragent.override”,“your useragent”) 一切都需要从firefox个人资料中设置。