- 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
- Web程序設(shè)計及應(yīng)用
- 自己動手實現(xiàn)Lua:虛擬機、編譯器和標(biāo)準(zhǔn)庫
- PHP網(wǎng)絡(luò)編程學(xué)習(xí)筆記
- UML+OOPC嵌入式C語言開發(fā)精講
- SQL Server 2016數(shù)據(jù)庫應(yīng)用與開發(fā)習(xí)題解答與上機指導(dǎo)
- Visual Basic程序設(shè)計教程
- 深入淺出React和Redux
- Java Web開發(fā)詳解
- 蘋果的產(chǎn)品設(shè)計之道:創(chuàng)建優(yōu)秀產(chǎn)品、服務(wù)和用戶體驗的七個原則
- Android傳感器開發(fā)與智能設(shè)備案例實戰(zhàn)
- FPGA嵌入式項目開發(fā)實戰(zhàn)
- Java EE Web應(yīng)用開發(fā)基礎(chǔ)
- Java EE項目應(yīng)用開發(fā)
- Android嵌入式系統(tǒng)程序開發(fā)(基于Cortex-A8)
- WCF全面解析