5

I try to add cookie to the request in Selenium by JS. Documentation is obvious (http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_Options.html#addCookie) but my code snippet doesn't pass any cookie to PHP script(below) on the server.

Client JS code:

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder()
    .withCapabilities({'browserName': 'firefox'})
    .build();
driver.manage().addCookie("test", "cookie-1");
driver.manage().addCookie("test", "cookie-2").then(function () {
    driver.get('http://localhost/cookie.php').then(function () {
        driver.manage().addCookie("test", "cookie-3");
        driver.manage().getCookie('test').then(function (cookie) {
            console.log(cookie.value);
        });
        setTimeout(function () {
            driver.quit();
        }, 30000);
    });
});

Server PHP code:

<?php
    print_r($_COOKIE);
?>
kchod
  • 91
  • 1
  • 1
  • 6
  • console.log works properly, it returns "cookie-3". The problem is with PHP script which shows empty array. – kchod Mar 30 '16 at 10:08

3 Answers3

8

Your cookie is not sent because at the time you call addCookie, the domain is not defined. Here is example to send a cookie:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder()
    .withCapabilities({'browserName': 'firefox'})
    .build();

// set the domain
driver.get('http://127.0.0.1:1337/');

// set a cookie on the current domain
driver.manage().addCookie("test", "cookie-1");

// get a page with the cookie
driver.get('http://127.0.0.1:1337/');

// read the cookie
driver.manage().getCookie('test').then(function (cookie) {
   console.log(cookie);
});

driver.quit();
Florent B.
  • 41,537
  • 7
  • 86
  • 101
  • 2
    Thanks, it works. There was needed to use ``driver.get('http://domain')`` twice, before and after ``addCookie()`` – kchod Mar 30 '16 at 11:23
5

It helped me:

driver.manage().addCookie({name: 'notified', value: 'true'});
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    As you are a new contributor so to answer any question I would like to suggest you this article:- https://stackoverflow.com/help/how-to-answer. :) – code_aks Jan 18 '20 at 17:27
0

Cookie is sent as a header. You can simply set it in the header like:

$browser.addHeader('Cookie', "COO=KIE");

This can be done before sending the request.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • Did you use a library? I read that WebDriver does not have any API to set headers: https://stackoverflow.com/questions/15645093/setting-request-headers-in-selenium – baptx Sep 12 '20 at 09:45