Change Useragent in Selenium session

Highlighted
Senior Member

I am trying to change to a specific user agent string (for device emulation) using Selenium with Microsoft Edge.

Is there a documented way to do this?

 

Thanks,

Brian

 

1 Reply
Highlighted

@Brian Watts thanks for the question. You probably don't really just want to change the useragent string, as that only gets you so far. The only tests that will matter are tests that check the UA and make assumptions about what is supported. This is not a good best-practice. What you probably really want to do is actually use device emulation. 

 

Here is an example of how to do either, though:

 

var options = new EdgeOptions();
options.UseChromium = true;
options.AddArgument("--user-agent=New User Agent");
options.EnableMobileEmulation("iPhone X");

 

The above will actually NOT use the user-agent, because it will be overwritten by the iPhone X user agent, but if you remove that line, you can pass in the UA by itself. The string 'iPhone X' is from the emulator available in the DevTools for Edge (F12).

 

Hope that helps.

-John