How to extract network tab contents of Chrome Developer tools using Selenium

Viewed 447

I have been trying to write C# code to output the network tab contents of Developer tools as JSONArray, this is what I have so far:

*IWebDriver driver = new ChromeDriver(@"C:\Users\xxx\Downloads\chromedriver_win32");
driver.Navigate().GoToUrl("https://google.com");
String scriptToExecute = "var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var network = performance.getEntries() || {}; return network;";
String netData = ((IJavaScriptExecutor)driver).ExecuteScript(scriptToExecute).ToString();
Console.WriteLine(netData);*

And the other:

*IWebDriver driver = new ChromeDriver(@"C:\Users\xxx\Downloads\chromedriver_win32");
driver.Navigate().GoToUrl("https://google.com");
String ste = "Return window.performance.getEntries();";
String Timings = ((IJavaScriptExecutor)driver).ExecuteScript(ste).ToString();
Console.WriteLine(Timings);*

But my output is not giving the expected result. It looks like the String netData variable is returning as empty, thinking it is an issue with the Script. Any suggestions on a workaround for this?

1 Answers

You have to be aware of the return type of ExecuteScript method. If case of JS script

return window.performance.getEntries()

it will be

IReadOnlyCollection<object>

getEntries() returns an array of objects - in case of c# code it will be IDictionary<string, object> - key is a JS object property name, value is its value (:))

You have to do something like that:

var ste = "return window.performance.getEntries();";
var scriptResult = (IReadOnlyCollection<object>)(IJavaScriptExecutor)driver).ExecuteScript(ste);
var perfEntries = scriptResult.Select(e => ((IDictionary<string, object>)e); 
//(result will be an IEnumerable of IDictionary<string,object>), you can create a new, custom class to convert dictionaries to more verbose objects)

PS Please, try to stick to c# convention -> e.g. use string instead of String; name variable using lower case etc.

Related