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
- Load cookies from the cookiejar
- Hit a URL to check if the user is logged in
-
If not logged in
Log in, Save cookies to cookiejar
- 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
}
});