How to use addCustomRequestHeader method in selenium?
I was trying to use addCustomRequestHeader method to set a custom header for selenium requests. Given below is the source code
Selenium sel = new DefaultSelenium("localhost",4444,"*firefox","http://www.google.com");
sel.start("addCustomRequestHeader=true");
// sel.start();
sel.addCustomRequestHeader("mycustomheader","automation");
sel.open("http://www.google.com/");
This code didn't add the header to the request. I tried to look up the request headers using Fiddler. D开发者_StackOverflowoes any one here know what am I doing wrong here? Any help would be appreciated
You need to start the selenium in proxy injection mode
java -jar selenium-server-standalone.jar -proxyInjectionMode
You can then add custom requests headers like this (in Python)
sel.start("addCustomRequestHeader=true")
sel.add_custom_request_header("mycustomheader","automation")
sel.open('http://www.google.com')
To see if the custom header has been applied, check the tab that has the selenium server running. You should see something like this in the console messages
INFO - Command request: addCustomRequestHeader[mycustomheader, automation] on session
INFO - Got result: OK on session
In my case, running selenium in proxy injection mode is not acceptable so I have followed the approach of 'ModHeader' chrome extension to set the custom headers. This approached worked fine for me.
ModHeader Extension: https://github.com/mdamien/chrome-extensions-archive
Here is the code snippet
ChromeOptions chromeOpt = new ChromeOptions();
chromeOpt.addArguments("--no-sandbox");
System.setProperty("webdriver.chrome.args", "--disable-logging");
System.setProperty("webdriver.chrome.silentOutput", "true");
chromeOpt.addExtensions(new File("./ModHeader_v2.2.3.crx"));
WebDriver driver = new ChromeDriver(chromeOpt);
// set the context on the extension so the localStorage can be accessed
driver.get("chrome-extension://idgpnmonknjnojddfkpgkljpfnnfcklj/icon.png");
// setup ModHeader with two headers (token1 and token2)
((JavascriptExecutor)driver).executeScript(
"localStorage.setItem('profiles', JSON.stringify([{ " +
" title: 'Selenium', hideComment: true, appendMode: '', " +
" headers: [ " +
" {enabled: true, name: 'token1', value: 'testHeaderValue1', comment: ''}, " +
" {enabled: true, name: 'token2', value: 'testHeaderValue2', comment: ''} " +
" ], " +
" respHeaders: [], " +
" filters: [] " +
"}])); ");
driver.navigate().to("https://localhost:8443");
Fiddler Custom header snapshot
精彩评论