Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set cookie for request in CasperJS

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;"

like image 256
huangjingscnc Avatar asked Oct 19 '14 05:10

huangjingscnc


People also ask

Can you set cookie in GET request?

Also I would say it is perfectly acceptable to change or set a cookie in response for the GET request because you just return some data.

How do I set cookies in API?

set() The set() method of the cookies API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP Set-Cookie header during a request to a given URL.


1 Answers

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();
like image 79
Artjom B. Avatar answered Oct 07 '22 11:10

Artjom B.