Modify XHR response before sending it to client browser

504 Views Asked by At

I am new to Webproxy so need some guidance from the experts! I am running my UI automation tests in Saucelabs using Selenium remote web driver. When the client browser (in Saucelabs) tries to open a URL "https://abc.xyz.com/login", it makes a XHR request to get JSON file contents from the server. It then displays the UI elements based on the values in this JSON file. The JSON file looks like this..

{
"Login.Company": "Company",
"Login.Username": "User name",
"Login.Password": "Password"
}

I wish to modify the the values of these keys in the XHR response before it gets processed by the client browser so the client will see something like this...

{
    "Login.Company": "NewCompany",
    "Login.Username": "NewUser name",
    "Login.Password": "NewPassword"
}

My code looks like this...

public class WebProxyTests {
Proxy proxy;
BrowserMobProxyServer proxyServer;
private Proxy proxyConfig;
WebDriver driver;

@BeforeClass
void setup() {
    proxyServer = new BrowserMobProxyServer();
    proxyServer.start();
    
    // capture content as a HAR (HTTP Archive)
    // to process when test is complete
    proxyServer.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT,
                                      CaptureType.RESPONSE_CONTENT);
    proxyServer.newHar();
    
    proxyConfig = ClientUtil.createSeleniumProxy(proxyServer);
    
    FirefoxOptions options = new FirefoxOptions();
    options.setProxy(proxyConfig);
    System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\webdrivers\\geckodriver.exe");
    driver = new FirefoxDriver(options);
}

@Test
public void captureTraffic() throws InterruptedException {
    driver.get("https://abc.xyz.com/login");
    
    final Har httpMessages = proxyServer.getHar();
    for(HarEntry httpMessage : httpMessages.getLog().getEntries()){
        String url = httpMessage.getRequest().getUrl();
        if (url.contains("en-us.json")) {

            // Get the response data from XHR request
            HarContent data = httpMessage.getResponse().getContent();
            if (data != null) {
                System.out.println("DATA>>>>>>>>>" + data.getText());
            }
        }
    }
}

@AfterClass
/***
 * 
 */
void teardown() {
    driver.quit();
    proxyServer.abort();
}

Does anyone have any suggestions on how I would go about doing this? Any code examples would really be appreciated?

0

There are 0 best solutions below