Set cookie for request in CasperJS
Asked Answered
B

2

8

I want to load a page using CapserJS, but how can I send cookie which was exported from chrome's http request header at that page?

Such as:

"SUB=_2AkMjHt3gf8NhqwJRmPkQzG_qZIp_yA3EiebDAHzsJxJTHmMJ7IUyLkMN2K7WzRJvm-Tv3YY0xyZo; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WhCT_2hbJ1W1Cc4xfF-mFPo;"

Benoit answered 19/10, 2014 at 5:57 Comment(0)
V
6

There are multiple ways, but the easiest would be to use the page.addCookie or phantom.addCookie functions which PhantomJS provides, but you would have to set the domain (and path). Keep in mind that page.addCookie has to be done on a loaded page whereas phantom.addCookie can be done before.

var cookie = "someCookieName=Value; otherName=Value";
var domain = "example.com";
cookie.split(";").forEach(function(pair){
    pair = pair.split("=");
    phantom.addCookie({
      'name': pair[0],
      'value': pair[1],
      'domain': domain
    });
});

casper.start("http://example.com", function(){
    // check that cookie was indeed set:
    this.capture("screen.png");
}).run();
Voluble answered 19/10, 2014 at 8:59 Comment(1)
@user2518430 I have no idea why some people have a problem with this, but I can say that the domain property is very important. Here is an example script where it works for me. Create a screenshot with the addCookie call and one without to see whether there is a difference.Voluble
B
1

You could try to set the cookie headers directly like this:

casper.start().thenOpen('http://yoururl', {
    headers:{ "Cookie" : "CookieName=cookieValue" }
  }, function() {
    // ...
});
Bugs answered 20/7, 2017 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.