Jürgen Paul
Jürgen Paul

Reputation: 15007

phantom.addCookie doesn't work

Here's an example that I made:

/* global phantom:false */

var page = require('webpage').create();
var cookies = require('./cookie');

for (var i=0; i<cookies.length; i++) {
  (function(item){
    console.log('Add cookie:', item.name + '=' + item.value);
    phantom.addCookie({
      name: item.name,
      value: item.value,
      domain: item.domain,
      path: item.path,
      httponly: item.httpOnly,
      secure: item.secure,
      expires: item.expirationDate
    });
  })(cookies[i]);
}


page.open('http://www.html-kit.com/tools/cookietester/', function() {
  page.render('example.png');
  phantom.exit();
});

and the cookie file:

[{
    "domain": ".www.html-kit.com",
    "expirationDate": 1387428974.142711,
    "hostOnly": false,
    "httpOnly": false,
    "name": "TestCookie_Name_201312160042",
    "path": "/",
    "secure": false,
    "session": false,
    "storeId": "0",
    "value": "TestCookie_Value_230042"
}]

For an unknown reason it doesn't work for me:

enter image description here

Upvotes: 1

Views: 4318

Answers (1)

PasteBT
PasteBT

Reputation: 2198

For phantomJS 1.9.2, cookie works like this:

var page = require('webpage').create();

phantom.addCookie({
  'name'     : 'TestCookie_Name_201312174009',   /* required property */
  'value'    : 'TestCookie_Value_164009',  /* required property */
  'domain'   : 'www.html-kit.com',        /* required property */
  'path'     : '/',
  'httponly' : true,
  'secure'   : false,
  'expires'  : (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */
});


page.open('http://www.html-kit.com/tools/cookietester/', function() {
    //console.log(page.plainText);
    page.render('example.png');
    for (var i = 0; i < page.cookies.length; i++) {
        console.log(page.cookies[i].name + "=" + page.cookies[i].value);
    }
    phantom.exit();
});

save as cookie.js then run with

phantomjs cookie.js

Please be noticed, cookie name and value should has special pattern, otherwise html-kit looks not accept it.

If you want to save the cookie for later use, can add --cookies-file option

Upvotes: 1

Related Questions