Security update for Core, with self-updated composer
[yaffs-website] / node_modules / phridge / lib / Page.js
1 "use strict";
2
3 var serializeFn = require("./serializeFn.js");
4 var phantomMethods = require("./phantom/methods.js");
5
6 var slice = Array.prototype.slice;
7
8 /**
9  * A wrapper to run code within the context of a specific PhantomJS webpage.
10  *
11  * @see http://phantomjs.org/api/webpage/
12  * @param {Phantom} phantom the parent PhantomJS instance
13  * @param {number} id internal page id
14  * @constructor
15  */
16 function Page(phantom, id) {
17     Page.prototype.constructor.apply(this, arguments);
18 }
19
20 /**
21  * The parent phantom instance.
22  *
23  * @type {Phantom}
24  */
25 Page.prototype.phantom = null;
26
27 /**
28  * The internal page id.
29  *
30  * @private
31  * @type {number}
32  */
33 Page.prototype._id = null;
34
35 /**
36  * Initializes the page instance.
37  *
38  * @param {Phantom} phantom
39  * @param {number} id
40  */
41 Page.prototype.constructor = function (phantom, id) {
42     this.phantom = phantom;
43     this._id = id;
44 };
45
46 /**
47  * Stringifies the given function fn, sends it to PhantomJS and runs it in the context of a particular PhantomJS webpage.
48  * The PhantomJS webpage will be available as `this`. You may prepend any number of arguments which will be passed
49  * to fn inside of PhantomJS. Please note that all arguments should be stringifyable with JSON.stringify().
50  *
51  * @param {...*} args
52  * @param {Function} fn
53  * @returns {Promise}
54  */
55 Page.prototype.run = function (args, fn) {
56     args = slice.call(arguments);
57
58     fn = args.pop();
59
60     return this.phantom._send({
61         action: "run-on-page",
62         data: {
63             src: serializeFn(fn, args),
64             pageId: this._id
65         }
66     }, args.length === fn.length);
67 };
68
69 /**
70  * Runs a function inside of PhantomJS to cleanup memory. Call this function if you intent to not use the page-object
71  * anymore.
72  *
73  * @see http://msdn.microsoft.com/en-us/library/system.idisposable.aspx
74  * @returns {Promise}
75  */
76 Page.prototype.dispose = function () {
77     var self = this;
78
79     return this.run(this._id, phantomMethods.disposePage)
80         .then(function () {
81             self.phantom = null;
82         });
83 };
84
85 module.exports = Page;