- PhantomJS Cookbook
- Rob Friesel
- 840字
- 2021-07-16 11:37:57
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
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 cookiescookiesEnabled
: This is a Boolean indicating whether cookies are enabledaddCookie(cookieObject)
: This adds the defined cookie to the CookieJardeleteCookie(cookieName)
: This removes the named cookie from the CookieJarclearCookies()
: 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:
- We create a
webpage
object. - We check
phantom.cookiesEnabled
and write a message if cookies are not enabled. - We open the target URL (
http://localhost:3000/cookie-demo
); in the callback function, we checkstatus
and exit PhantomJS with a warning message if it is not successful. - If the request is successful, we iterate through the original cookies using the standard
forEach
function on thephantom.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 firstphantom.cookies
access to outside of theopen
callback, we may see cookies from the last time we accessed this particular URL. - 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 returnfalse
. - 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. - 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
- Spring Boot開發與測試實戰
- Git Version Control Cookbook
- LabVIEW 2018 虛擬儀器程序設計
- LabVIEW Graphical Programming Cookbook
- C和C++安全編碼(原書第2版)
- Twilio Best Practices
- Flask Web開發入門、進階與實戰
- 跟老齊學Python:輕松入門
- Python機器學習編程與實戰
- Python數據可視化之Matplotlib與Pyecharts實戰
- Android系統級深入開發
- Fastdata Processing with Spark
- Android編程權威指南(第4版)
- 例說FPGA:可直接用于工程項目的第一手經驗
- Mastering Drupal 8