How to add headers or parameters to an HTTP request handled with Selenium Webdriver? How to add headers or parameters to an HTTP request handled with Selenium Webdriver? selenium selenium

How to add headers or parameters to an HTTP request handled with Selenium Webdriver?


You can try evaluating browsermob-proxy. It helps in manipulating the headers.https://github.com/webmetrics/browsermob-proxy. Integrating with webdriver is simple. You just need to start the driver with the proxy values set.


Might be useful for others who are looking for a solution

This is how I fixed the problem in my case. Hopefully, might be helpful for anyone with a similar setup.

  1. Add the ModHeader extension to the chrome browser

How to download the Modheader? Link

ChromeOptions options = new ChromeOptions();options.addExtensions(new File(C://Downloads//modheader//modheader.crx));// Set the Desired capabilities DesiredCapabilities capabilities = new DesiredCapabilities();capabilities.setCapability(ChromeOptions.CAPABILITY, options);// Instantiate the chrome driver with capabilitiesWebDriver driver = new RemoteWebDriver(new URL(YOUR_HUB_URL), options);
  1. Go to the browser extensions and capture the Local Storage context ID of the ModHeader

Capture ID from ModHeader

  1. Navigate to the URL of the ModHeader to set the Local Storage Context

.

// set the context on the extension so the localStorage can be accesseddriver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/_generated_background_page.html");Where `idgpnmonknjnojddfkpgkljpfnnfcklj` is the value captured from the Step# 2
  1. Now add the headers to the request using Javascript

.

   ((Javascript)driver).executeScript(         "localStorage.setItem('profiles', JSON.stringify([{  title: 'Selenium', hideComment: true, appendMode: '',              headers: [                                       {enabled: true, name: 'token-1', value: 'value-1', comment: ''},               {enabled: true, name: 'token-2', value: 'value-2', comment: ''}             ],                                       respHeaders: [],             filters: []          }]));");

Where token-1, value-1, token-2, value-2 are the request headers and values that are to be added.

  1. Now navigate to the required web-application.

    driver.get("your-desired-website");