Skip to content

User agent override

aqualityAutomation edited this page Mar 17, 2023 · 1 revision

Chrome DevTools Protocol provides two methods for overriding the browser user agent: Network.setUserAgentOverride and Emulation.setUserAgentOverride. The difference between them is not much, often either of these methods can be used. But if, for example, you need to explicitly override the accept-language header of the request, then Emulation.setUserAgentOverride should be used. In Aquality Selenium the work with Network.setUserAgentOverride is implemented in NetworkHandling class, with Emulation.setUserAgentOverride - in EmulationHandling class.

The user agent override is demonstrated in the OverrideUserAgenTest class. All tests in a given class set the same user agent and language (where possible), as shown below. image

EmulationHandling

The EmulationHandling class provides the following methods to override the user agent:

void setUserAgentOverride(String userAgent, Optional acceptLanguage, Optional platform) - overrides user agent, language and platform (e.g. Win32, Linux x86_64, etc.); void setUserAgentOverride(String userAgent) - overrides browser user agent; void setUserAgentOverride(Map<String, Object> params) - overrides the user agent via parameters that are directly used in the DevTools command for the Emulation.setUserAgentOverride method.. The overrideUserAgentViaNetworkTest, overrideUserAgentByParametersMapTest, and overrideUserAgentAndLanguageTest tests demonstrate how these methods work. image image image

NetworkHandling

The NetworkHandling class provides the following methods to override the user agent:

void setUserAgent(String userAgent) - sets the user agent for the browser; void setUserAgent(Network.UserAgent userAgent) - uses the Network.UserAgent class to set the user agent. image

DevToolsHandling

Here is demonstrated overriding the user agent by explicitly calling CDP commands using methods of the DevToolsHandling class. image In the overrideUserAgentByVersionSpecificCommandTest, the user agent is overridden by passing the result of Emulation.setUserAgentOverride() method to sendCommand() method. In this test, in addition to the user agent, the browser language is also overridden. image In the overrideUserAgentByCdpCommandTest the user agent is overridden by the executeCdpCommand() method (Emulation.setUserAgentOverride command).