Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use persisted cookies from a file using phantomjs

Tags:

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.

like image 476
Arun Avatar asked Sep 11 '13 11:09

Arun


1 Answers

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  }   }); 
like image 66
Jason Avatar answered Sep 19 '22 05:09

Jason