I'm currently using version 4.0.0-alpha5 of the Selenium Webdriver NuGet package. So this code only works when the DevTools are open in Chrome Version 98, but I don't understand why. As far as I know, should this always work, but the only thing that always works is the offline state.
devTools = driver as IDevTools;
session = devTools.CreateDevToolsSession();
EmulateNetworkConditionsCommandSettings command = new EmulateNetworkConditionsCommandSettings();
command.Latency = latencyInMilliseconds;
command.DownloadThroughput = downloadLimitKbps * 1024; // Kilobytes to bytes per second
command.UploadThroughput = uploadLimitKbps * 1024; // Kilobytes to bytes per second
command.Offline = false;
session.Network.EmulateNetworkConditions(command);
//session.SendCommand(command);
You will also find this code on this site, so I don't know what I'm doing wrong. Maybe this is a bug.
A solution would be to just open the DevTools during the test, but pressing a hotkey with selenium like F12 or any other Devtools hotkey doesn't work for me. I tried it with Actions and also with sending keys on an object like it is described here.
Another solution would maybe be to directly execute a CDP command, but I only found examples in Java and didn't find out how to do this. This is how you do it in Java:
driver.executeCdpCommand(commandString);
Thank you for reading, any help would be really appreciated.
My issue was that I forgot to add the Network.Enable command, so don't forget to call it before you do the other stuff. This is the code I use now, without being version specific. (works until Selenium 4.0 alpha 5)
public void LimitNetwork(int latencyInMilliseconds, long downloadLimitMbps, long uploadLimitMbps)
{
IDevTools devTools = driver as IDevTools;
session = devTools.CreateDevToolsSession();
session.Network.Enable(new EnableCommandSettings());
EmulateNetworkConditionsCommandSettings command = new EmulateNetworkConditionsCommandSettings();
command.Latency = latencyInMilliseconds;
command.DownloadThroughput = downloadLimitMbps * 125000; // Mbps to bytes per second
command.UploadThroughput = uploadLimitMbps * 125000; // Mbps to bytes per second
command.Offline = false;
session.Network.EmulateNetworkConditions(command);
}
If session.Network.EmulateNetworkConditions doesn't work you can also try session.SendCommand(command);