Inspecting websocket response in webdriver

771 views Asked by At

Is there any way i can call a api(in java language) to inspect websocket response of a webpage for some verification in the webdriver tests of that webpage. Sorry for being generic with the question but any pointers will help.

1

There are 1 answers

1
Exboy On
import org.json.JSONObject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.util.logging.Level;

public class WebSocketLogging {

private static WebDriver driver;

public static void main(String[] args) throws InterruptedException {
    LoggingPreferences loggingprefs = new LoggingPreferences();
    loggingprefs.enable(LogType.PERFORMANCE, Level.ALL);

    DesiredCapabilities cap = new DesiredCapabilities().chrome();
    cap.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);
    
    System.setProperty("webdriver.chrome.driver", "C:\\Sarabjeet\\Box\\chromedriver.exe");

    driver = new ChromeDriver(cap);
    driver.navigate().to("https://web-demo.adaptivecluster.com/");
    Thread.sleep(5000);
    LogEntries logEntries = driver.manage().logs().get(LogType.PERFORMANCE);

    driver.close();
    driver.quit();
    logEntries.forEach(entry->{
        JSONObject messageJSON = new JSONObject(entry.getMessage());
        String method = messageJSON.getJSONObject("message").getString("method");
        if(method.equalsIgnoreCase("Network.webSocketFrameSent")){
            System.out.println("Message Sent: " + messageJSON.getJSONObject("message").getJSONObject("params").getJSONObject("response").getString("payloadData"));
        }else if(method.equalsIgnoreCase("Network.webSocketFrameReceived")){
            System.out.println("Message Received: " + messageJSON.getJSONObject("message").getJSONObject("params").getJSONObject("response").getString("payloadData"));
        }
    });
}

}