Chapter 8. Cookies

Cookies are mostly used to save small information about users' activities during visits on a particular site. Most often, this information is used when the user visits the site again, like knowing which particular search the user used or the page from where the user left off. PhantomJS supports cookies and has a minimal API to manage cookies within the phantom object.

Default cookies are enabled in PhantomJS, and we can also disable cookies by setting the following property:

phantom.cookiesEnabled = false;

Reading cookies

Each cookie that a web page generates or creates will be stored in the phantom.cookies object.

To retrieve all the cookies, we access the cookies member. Let us print the cookies object:

page.open(url, function(status) {
  if ( status === "success" ) {
    console.log(phantom.cookies);
    phantom.exit(0);
  }
});

If there are cookies in the website that we are accessing, then you should see output similar to the following screenshot:

Reading cookies

Based on the preceding output, .yahoo.com has several cookies. These cookies vary on the website or URL. Each cookie is in object form, which can be viewed as a JSON object. Each cookie object will have the following properties:

{
  'name'    : 'name of cookie',
  'value'   : 'value associated',
  'domain'  : 'cookie domain',
  'path'    : 'cookie path',
  'httponly': (true or false),
  'secure'  : (true or false),
  'expires' : integer value of cookie expiration in seconds
}

If we change a bit of our code, we can make the cookies readable by converting the JSON object into a string version using the following code:

console.log(JSON.stringify(phantom.cookies, null, 4));

Then, we will have a more readable output, as shown in the following screenshot:

Reading cookies
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.34.31