Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium JS add cookie to request

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);
?>
like image 518
kchod Avatar asked Mar 30 '16 10:03

kchod


People also ask

Can selenium handle cookies?

Selenium WebDriver provides multiple commands for handling the cookies in a website. These Selenium cookies APIs provide you the required mechanism for interacting and querying the cookies. In Selenium Java, these methods are a part of the org. openqa.

How can selenium developer clear a specific cookie information?

We can delete cookies on all domains with Selenium. The method deleteAllCookies is used to delete all cookies from the present domain. First, we shall add cookies, then get them and finally delete all the cookies.

How do I disable cookies in selenium?

printStackTrace(); } DesiredCapabilities capabilities = DesiredCapabilities. chrome(); capabilities. setCapability("disable-restore-session-state", true); driver = new ChromeDriver(service, capabilities); selenium-webdriver.


2 Answers

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();
like image 134
Florent B. Avatar answered Sep 21 '22 22:09

Florent B.


It helped me:

driver.manage().addCookie({name: 'notified', value: 'true'});
like image 26
Konstantin Konstantynin Avatar answered Sep 21 '22 22:09

Konstantin Konstantynin