How can I use persisted cookies from a file using phantomjs

I have some authentication requried to hit a particular url. In browser I need to login only once, as for other related urls which can use the session id from the cookie need not required to go to the login page. Similarly, can I use the cookie generated in the cookie file using --cookies-file=cookies.txt in the commandline in phantomjs to open other page which requires the same cookie detail.

Please suggest.


Phantom JS and cookies

--cookies-file=cookies.txt will only store non-session cookies in the cookie jar. Login and authentication is more commonly based on session cookies.

What about session cookies?

To save these is quite simple, but you should consider that they will likely expire quickly.

You need to write your program logic to consider this. For example

  1. Load cookies from the cookiejar
  2. Hit a URL to check if the user is logged in
  3. If not logged in

    Log in, Save cookies to cookiejar

  4. continue with processing

Example

var fs = require('fs');
var CookieJar = "cookiejar.json";
var pageResponses = {};
page.onResourceReceived = function(response) {
    pageResponses[response.url] = response.status;
    fs.write(CookieJar, JSON.stringify(phantom.cookies), "w");
};
if(fs.isFile(CookieJar))
    Array.prototype.forEach.call(JSON.parse(fs.read(CookieJar)), function(x){
        phantom.addCookie(x);
    });

page.open(LoginCheckURL, function(status){
 // this assumes that when you are not logged in, the server replies with a 303
 if(pageResponses[LoginCheckURL] == 303)
 {  
    //attempt login
    //assuming a resourceRequested event is fired the cookies will be written to the jar and on your next load of the script they will be found and used
 }


});

The file created by the option --cookies-file=cookies.txt is serialized from CookieJar: there are extra characters and it's sometimes difficult to parse.

It may looks like:

[General]
cookies="@Variant(\0\0\0\x7f\0\0\0\x16QList<QNetworkCookie>\0\0\0\0\x1\0\0\0\v\0\0\0{__cfduid=da7fda1ef6dd8b38450c6ad5632...

I used in the past phantom.cookies. This array will be pre-populated by any existing Cookie data stored in the cookie file specified in the PhantomJS startup config/command-line options, if any. But you can also add dynamic cookie by using phantom.addCookie.

A basic example is

phantom.addCookie({
    'name':     'Valid-Cookie-Name',   /* required property */
    'value':    'Valid-Cookie-Value',  /* required property */
    'domain':   'localhost',           /* required property */
    'path':     '/foo',
    'httponly': true,
    'secure':   false,
    'expires':  (new Date()).getTime() + (1000 * 60 * 60)   /* <-- expires in 1 hour */
});

With these methods, it's not so difficult to implement your own cookie management logic.