I am working in a java+selenium automation framework, and I want try something different- capture some network traffic with javascript within an existing @Test. Javascript because I had far too many problems with browsermob. I want to capture a piece, or two, of the network traffic response; then eventually send/store it some where like S3 for further db validation due to propagation delays.
I am blocked after getting the network response.
I have gotten it as a List object, and can loop through it with an if statement to get what I want.
JavascriptExecutor js = (JavascriptExecutor) driver;
String javaScriptScript = "var performance = window.performance || window.mozPerformance || "
+ "window.msPerformance || window.webkitPerformance || "
+ "{}; var network = performance.getEntries() || {}; return JSON.stringify(network);";
List<Object> results = (List<Object>) js.executeScript(javaScriptScript)
for (Object result : results) {
if (result.toString().contains("foo")) {
System.out.println("foo=" + result.toString()); // foo = "name": "foo"
}
if (result.toString().contains("bar")) { // bar = "name": "bar"
System.out.println("bar=" + result.toString());
}
}`
I even found out I can update the js from:
return network;
to:
return JSON.stringify(network);
While I am comfortable with this so far, I feel I should be using json here. So I can get to this implementation which gives prettier output:
String results = (String) js.executeScript(javaScriptScript);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(results);
String prettyJsonString = gson.toJson(je);
System.out.println(prettyJsonString);`
But I am less comfortable iterating through the json vs the List, and picking out what I need (e.g., name:foo) even though it should be easier?
What is the best approach, and if it is json, how do I iterate and capture what pieces I needs.
TIA.