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.
--cookies-file=cookies.txt
will only store non-session cookies in the cookie jar. Login and authentication is more commonly based on 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
If not logged in
Log in, Save cookies to cookiejar
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 } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With