官术网_书友最值得收藏!

Managing cookies with the phantom object

In this recipe, we will discuss how to work with cookies in PhantomJS. The phantom object exposes two properties (cookies and cookiesEnabled) and three methods (addCookie, clearCookie, and deleteCookie) that we can use to inspect and manipulate cookies at runtime.

Getting ready

To run this recipe, we may wish to run PhantomJS with persistent cookies using the cookies-file command-line argument.

The script in this recipe is available in the downloadable code repository as recipe02.js under chapter02. If we run the provided example script, we must change to the root directory for the book's sample code.

Lastly, the script in this recipe runs against the demo site that is included with the cookbook's sample code repository. To run the demo site, we must have Node.js installed. In a separate terminal, change to the phantomjs-sandbox directory (in the sample code's directory) and start the app with the following command:

node app.js

How to do it…

Consider the following script:

var page = require('webpage').create(),
    url  = 'http://localhost:3000/cookie-demo';

if (!phantom.cookiesEnabled) {
  console.log('Note: cookies not enabled.');
}

page.open(url, function(status) {
  if (status === 'success') {
    console.log('We start with these cookies:');
    phantom.cookies.forEach(function(c) {
      console.info(JSON.stringify(c, undefined, 2));
    });
    phantom.addCookie({
      name: 'jerry',
      value: 'black-and-white',
      domain: 'localhost'
    });

    console.log('Added the "jerry" cookie; how many now? ' +
      phantom.cookies.length);
    
    phantom.deleteCookie('jerry');
    console.log('Deleted the "jerry" cookie; how many now? ' +
      phantom.cookies.length);

    phantom.clearCookies();

    console.log('How many cookies after a clear? ' +
      phantom.cookies.length);

    phantom.exit();    
  } else {
    console.error('Something is wrong!');
    phantom.exit(1);
  }
});

Given the preceding script, enter the following at the command line:

phantomjs --cookies-file=cookie-jar.txt chapter02/recipe02.js

Note

PhantomJS will create cookie-jar.txt for us; there is no need to create it manually.

Our output should look like the following:

We start with these cookies:
{
 "domain": "localhost",
 "expires": "Thu, 19 Dec 2013 03:04:33 GMT",
 "expiry": 1387422273,
 "httponly": false,
 "name": "rob",
 "path": "/cookie-demo",
 "secure": false,
 "value": "chocolate-chip"
}
{
 "domain": "localhost",
 "expires": "Thu, 19 Dec 2013 03:04:33 GMT",
 "expiry": 1387422273,
 "httponly": false,
 "name": "dave",
 "path": "/cookie-demo",
 "secure": false,
 "value": "oatmeal-raisin"
}
Added the "jerry" cookie; how many now? 3
Deleted the "jerry" cookie; how many now? 2
How many cookies after a clear? 0

How it works…

PhantomJS' global phantom object exposes properties and methods to inspect and manipulate the runtime environment, including two properties and three methods for working with cookies. They are:

  • cookies: This is an array holding the cookies
  • cookiesEnabled: This is a Boolean indicating whether cookies are enabled
  • addCookie(cookieObject): This adds the defined cookie to the CookieJar
  • deleteCookie(cookieName): This removes the named cookie from the CookieJar
  • clearCookies(): This is to remove all cookies from the CookieJar

Tip

We can find the cookie-related properties and methods discussed in the PhantomJS API documentation for the phantom object at http://phantomjs.org/api/phantom/.

These methods are in addition to any inspection or manipulation of cookies that occur as a result of server- or client-side script operations. In other words, remote servers can still get/set cookies on the HTTP request or response, and JavaScript running on the page can do the same, but PhantomJS provides a way for us to perform additional operations on cookies.

In our preceding example script, we perform the following actions:

  1. We create a webpage object.
  2. We check phantom.cookiesEnabled and write a message if cookies are not enabled.

    Tip

    Note that phantom.cookiesEnabled is not a read-only property. When accessed, it returns a Boolean indicating whether the CookieJar is enabled; it is enabled (returns true) by default. However, we can set this property to false if we wish to disable cookies.

  3. We open the target URL (http://localhost:3000/cookie-demo); in the callback function, we check status and exit PhantomJS with a warning message if it is not successful.
  4. If the request is successful, we iterate through the original cookies using the standard forEach function on the phantom.cookies array, printing each one to the console.

    Tip

    Note that phantom.cookies contains all the cookies that the runtime environment has currently loaded, and this may include cookies from previous sessions. For example, if we already have cookies in our CookieJar file and move the first phantom.cookies access to outside of the open callback, we may see cookies from the last time we accessed this particular URL.

  5. We add a cookie using phantom.addCookie, which takes a single argument: an object that describes the cookie's properties. Note that the cookie object must contain a name, a value, and a domain property, or the method call will fail and return false.
  6. We delete the cookie we just added using phantom.deleteCookie, which takes a single argument: a string for the name of the cookie we wish to delete.

    Tip

    If we do not know the name of the cookie, we need to iterate through the phantom.cookies array to identify the name of the cookie we wish to delete.

  7. We delete all cookies by calling phantom.clearCookies. This is functionally equivalent to calling the clear cookies command from a menu or dialog in any other browser. Lastly, we exit the PhantomJS runtime.

See also

  • The Running PhantomJS with cookies recipe in Chapter 1, Getting Started with PhantomJS
主站蜘蛛池模板: 牟定县| 静宁县| 宜城市| 富锦市| 方山县| 柘荣县| 舟山市| 枣阳市| 弥渡县| 盐津县| 无棣县| 安仁县| 丘北县| 竹溪县| 蒲江县| 社会| 靖安县| 克什克腾旗| 淳化县| 谷城县| 睢宁县| 涟源市| 汨罗市| 西昌市| 吉林市| 资中县| 陇西县| 南京市| 扶风县| 邻水| 寻乌县| 电白县| 焦作市| 峨山| 墨玉县| 花莲县| 久治县| 建始县| 乌拉特前旗| 琼结县| 高陵县|