08-27-周三_17-09-29

This commit is contained in:
2025-08-27 17:10:05 +08:00
commit 86df397d8f
12735 changed files with 1145479 additions and 0 deletions

3
node_modules/phantom/.npmignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
node_modules
.test
.idea

18
node_modules/phantom/.travis.yml generated vendored Normal file
View File

@@ -0,0 +1,18 @@
sudo: false
language: node_js
# Add build chain config for Node GYP in Node 4.x
env:
- CXX=g++-4.8
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.8
node_js:
- "4.1"
- "4.0"
- "0.12"
- "0.11"
- "0.10"

57
node_modules/phantom/Cakefile generated vendored Normal file
View File

@@ -0,0 +1,57 @@
{spawn} = require 'child_process'
Promise = require 'bluebird'
bin = "./node_modules/.bin"
sh = "/bin/sh"
_runCmd = (prev, current) ->
prev.then ->
new Promise (resolve, reject) ->
args = ['-c', current]
child = spawn sh, args, {stdio: 'inherit'}
child.on 'error', reject
child.on 'exit', (code) ->
if (code or 0) is 0 then resolve() else reject()
run = (cmds...) ->
seq = cmds.reduce _runCmd, Promise.resolve()
seq.error (err) -> console.log 'Failed.', err
cleanup = ->
run "rm -rf .test .shim.js"
exit = (code = 0) ->
process.exit code
callbacks =
success: -> console.log 'Great Success!'
error: -> console.error 'Task failed.'
option '', '--test-regex [TEST_RE]', 'Run tests matching TEST_RE.'
task "clean", "cleanup build and test artifacts", ->
cleanup().then -> console.log 'All clean.'
task "build", "coffee-compile and browserify phantom", ->
run(
"#{bin}/coffee -c phantom.coffee"
"#{bin}/browserify -t coffeeify shim.coffee -o .shim.js"
"cat pre_shim.js .shim.js > shim.js"
)
.then(callbacks.success, callbacks.error)
.finally cleanup
task "test", "run phantom's unit tests", (options) ->
invoke('build').then ->
batch = run(
"#{bin}/coffee -o .test -c test/*.coffee"
"cp test/*.gif test/*.js .test/"
"#{bin}/vows --spec .test/#{options['test-regex'] ? '*'}.js"
)
batch
.then(callbacks.success, callbacks.error)
.then(cleanup)
.catch -> exit(1)

154
node_modules/phantom/README.markdown generated vendored Normal file
View File

@@ -0,0 +1,154 @@
# PhantomJS bridge for NodeJS
[![Build Status](https://travis-ci.org/sgentle/phantomjs-node.svg?branch=master)](https://travis-ci.org/sgentle/phantomjs-node) [![NPM Version](https://badge.fury.io/js/phantom.svg)](https://badge.fury.io/js/phantom)
"It sure would be neat if [PhantomJS](http://phantomjs.org/) was a NodeJS module", I hear you say. Well, wait no longer! This node module implements a nauseatingly clever bridge between Phantom and Node, so that you can use all your favourite PhantomJS functions without leaving NPM behind and living in a cave.
## Installation
First, make sure PhantomJS is installed. This module expects the ```phantomjs``` binary to be in PATH somewhere. In other words, type this:
$ phantomjs
If that works, so will phantomjs-node. It's only been tested with PhantomJS 1.3, and almost certainly doesn't work with anything older.
Install it like this:
npm install phantom
For a brief introduction continue reading, otherwise **go to the [Wiki page](https://github.com/sgentle/phantomjs-node/wiki) for more information!**
## How do I use it?
Use it like this in Coffeescript:
```coffeescript
phantom = require 'phantom'
phantom.create (ph) ->
ph.createPage (page) ->
page.open "http://www.google.com", (status) ->
console.log "opened google? ", status
page.evaluate (-> document.title), (result) ->
console.log 'Page title is ' + result
ph.exit()
```
In Javascript:
```js
var phantom = require('phantom');
phantom.create(function (ph) {
ph.createPage(function (page) {
page.open("http://www.google.com", function (status) {
console.log("opened google? ", status);
page.evaluate(function () { return document.title; }, function (result) {
console.log('Page title is ' + result);
ph.exit();
});
});
});
});
```
### Use it in Windows
It would use `dnode` with `weak` module by default. It means that you need to setup `node-gyp` with Microsoft VS2010 or VS2012, which is a huge installation on Windows.
`dnodeOpts` property could help you to control dnode settings, so you could disable `weak` by setting it `false` to avoid that complicated installations.
```js
var phantom = require('phantom');
phantom.create(function (ph) {
ph.createPage(function (page) {
/* the page actions */
});
}, {
dnodeOpts: {
weak: false
}
});
```
### Use it in restricted enviroments
Some enviroments (eg. [OpenShift](https://help.openshift.com/hc/en-us/articles/202185874-I-can-t-bind-to-a-port)) have special requirements that are difficult or impossible to change, especifficaly: hostname/ip and port restrictions for the internal communication server and path for the phantomjs binary.
By default, the hostname/ip used for this will be `localhost`, the port will be port `0` and the phantomjs binary is going to be assumed to be in the `PATH` enviroment variable, but you can use specific configurations using an `options` object like this:
```js
var options = {
port: 16000,
hostname: "192.168.1.3",
path: "/phantom_path/"
}
phantom.create(function, options);
```
## Functionality details
You can use all the methods listed on the [PhantomJS API page](http://phantomjs.org/api/)
Due to the async nature of the bridge, some things have changed, though:
* Return values (ie, of ```page.evaluate```) are returned in a callback instead
* ```page.render()``` takes a callback so you can tell when it's done writing the file
* Properties can't be get/set directly, instead use ```page.get('version', callback)``` or ```page.set('viewportSize', {width:640,height:480})```, etc. Nested objects can be accessed by including dots in keys, such as ```page.set('settings.loadImages', false)```
* Callbacks can't be set directly, instead use ```page.set('callbackName', callback)```, e.g. ```page.set('onLoadFinished', function(success) {})```
* onResourceRequested takes a function that executes in the scope of phantom which has access to ```request.abort()```, ```request.changeUrl(url)```, and ```request.setHeader(key,value)```. The second argument is the callback which can execute in the scope of your code, with access to just the requestData. This function can apply extra arguments which can be passed into the first function e.g.
```
page.onResourceRequested(
function(requestData, request, arg1, arg2) { request.abort(); },
function(requestData) { console.log(requestData.url) },
arg1, arg2
);
```
```ph.createPage()``` makes new PhantomJS WebPage objects, so use that if you want to open lots of webpages. You can also make multiple phantomjs processes by calling ```phantom.create('flags', { port: someDiffNumber})``` multiple times, so if you need that for some crazy reason, knock yourself out!
Also, you can set exit callback, which would be invoked after ```phantom.exit()``` or after phantom process crash:
```
phantom.create('flags', { port: 8080, onExit: exitCallback})
```
You can also pass command line switches to the phantomjs process by specifying additional args to ```phantom.create()```, eg:
```coffeescript
phantom.create '--load-images=no', '--local-to-remote-url-access=yes', (page) ->
```
or by specifying them in the options object:
```coffeescript
phantom.create {parameters: {'load-images': 'no', 'local-to-remote-url-access': 'yes'}}, (page) ->
```
If you need to access the [ChildProcess](http://nodejs.org/api/child_process.html#child_process_class_childprocess) of the phantom process to get its PID, for instance, you can access it through the `process` property like this:
```
phantom.create(function (ph) {
console.log('phantom process pid:', ph.process.pid);
});
```
##Note for Mac users
Phantom requires you to have the XCode Command Line Tools installed on your box, or else you will get some nasty errors (`xcode` not found or `make` not found). If you haven't already, simply install XCode through the App Store, then [install the command line tools](http://stackoverflow.com/questions/6767481/where-can-i-find-make-program-for-mac-os-x-lion).
## How does it work?
Don't ask. The things these eyes have seen.
## No really, how does it work?
I will answer that question with a question. How do you communicate with a process that doesn't support shared memory, sockets, FIFOs, or standard input?
Well, there's one thing PhantomJS does support, and that's opening webpages. In fact, it's really good at opening web pages. So we communicate with PhantomJS by spinning up an instance of ExpressJS, opening Phantom in a subprocess, and pointing it at a special webpage that turns socket.io messages into ```alert()``` calls. Those ```alert()``` calls are picked up by Phantom and there you go!
The communication itself happens via James Halliday's fantastic [dnode](https://github.com/substack/dnode) library, which fortunately works well enough when combined with [browserify](https://github.com/substack/node-browserify) to run straight out of PhantomJS's pidgin Javascript environment.
If you'd like to hack on phantom, please do! You can run the tests with ```cake test``` or ```npm test```, and rebuild the coffeescript/browserified code with ```cake build```. You might need to ```npm install -g coffee-script``` for cake to work.

116
node_modules/phantom/package.json generated vendored Normal file
View File

@@ -0,0 +1,116 @@
{
"_args": [
[
{
"name": "phantom",
"raw": "phantom@^0.8.3",
"rawSpec": "^0.8.3",
"scope": null,
"spec": ">=0.8.3 <0.9.0",
"type": "range"
},
"/root/gitbook/node_modules/gitbook-plugin-mermaid"
]
],
"_from": "phantom@>=0.8.3 <0.9.0",
"_id": "phantom@0.8.4",
"_inCache": true,
"_installable": true,
"_location": "/phantom",
"_nodeVersion": "5.1.0",
"_npmUser": {
"email": "findamir@gmail.com",
"name": "amir20"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "phantom",
"raw": "phantom@^0.8.3",
"rawSpec": "^0.8.3",
"scope": null,
"spec": ">=0.8.3 <0.9.0",
"type": "range"
},
"_requiredBy": [
"/gitbook-plugin-mermaid"
],
"_resolved": "https://registry.npmjs.org/phantom/-/phantom-0.8.4.tgz",
"_shasum": "ccdb53d88a9237fd355191277c58d97705aaaffd",
"_shrinkwrap": null,
"_spec": "phantom@^0.8.3",
"_where": "/root/gitbook/node_modules/gitbook-plugin-mermaid",
"author": {
"email": "sam@samgentle.com",
"name": "Sam Gentle"
},
"bugs": {
"url": "https://github.com/sgentle/phantomjs-node/issues"
},
"contributors": [
{
"email": "findamir@gmail.com",
"name": "Amir Raminfar"
}
],
"dependencies": {
"dnode": ">=1.2.2",
"shoe": "~0.0.15",
"traverse": "~0.6.3",
"win-spawn": "~2.0.0"
},
"deprecated": "This package is no longer maintained",
"description": "PhantomJS wrapper for Node",
"devDependencies": {
"bluebird": "~1.2.3",
"browserify": "10.0.0",
"coffee-script": "~1.9.2",
"coffeeify": "^1.1.0",
"express": "3.2.5",
"phantomjs": "~1.9.7-5",
"ps-tree": "~0.0.2",
"temp": "~0.4.0",
"vows": "~0.7.0"
},
"directories": {},
"dist": {
"integrity": "sha512-4ymlTVSn7szaKhT5msZ7/L/g/yqeGoWjwV5RdzK8ZlWQCTw3RQzPs8jsRbLu2F1TsSeyrg5S0jJ6qMMgPYAOUQ==",
"shasum": "ccdb53d88a9237fd355191277c58d97705aaaffd",
"signatures": [
{
"keyid": "SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA",
"sig": "MEUCIFmSLKxthcl7C6TwfiyiKhwecYbRbO5z1FrUJB8eOcNUAiEAh6G8UAJ2cWdHw1vDICiaKBA6Gto/UOcXzkrU93DrqJE="
}
],
"tarball": "https://registry.npmjs.org/phantom/-/phantom-0.8.4.tgz"
},
"engines": {
"node": ">=v0.8.0"
},
"gitHead": "7499b3767d0843eb69154c0e6fae3b22d8d7db41",
"homepage": "https://github.com/sgentle/phantomjs-node",
"license": "MIT",
"main": "phantom.js",
"maintainers": [
{
"email": "sam@samgentle.com",
"name": "sgentle"
},
{
"email": "findamir@gmail.com",
"name": "amir20"
}
],
"name": "phantom",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/sgentle/phantomjs-node.git"
},
"scripts": {
"prepublish": "cake build",
"test": "cake test"
},
"version": "0.8.4"
}

140
node_modules/phantom/phantom.coffee generated vendored Normal file
View File

@@ -0,0 +1,140 @@
dnode = require 'dnode'
http = require 'http'
shoe = require 'shoe'
spawn = require 'win-spawn'
# the list of phantomjs RPC wrapper
phanta = []
# @Description: starts and returns a child process running phantomjs
# @param: port:int
# @args: args:object
# @return: ps:object
startPhantomProcess = (binary, port, hostname, args) ->
spawn binary, args.concat([
__dirname + '/shim.js'
port
hostname
])
# @Description: kills off all phantom processes within spawned by this parent
# process when it is exits
cleanUp = ->
phantom.exit() for phantom in phanta
onSignalClean = (signal) ->
return ->
if process.listeners(signal).length is 1
process.exit(0)
process.on('exit', cleanUp)
process.on(signal, onSignalClean(signal)) for signal in ['SIGINT', 'SIGTERM']
# @Description: We need this because dnode does magic clever stuff with
# functions, but we want the function to make it intact to phantom
wrap = (ph) ->
ph.callback = (fn) ->
return '__phantomCallback__'+fn.toString()
ph._createPage = ph.createPage
ph.createPage = (cb) ->
ph._createPage (page) ->
page._evaluate = page.evaluate
page.evaluate = (fn, cb, args...) ->
page._evaluate.apply(page, [fn.toString(), cb].concat(args))
page._onResourceRequested = page.onResourceRequested
# can apply extra args which will be passed to phantomjs
# onResourceRequested scope
page.onResourceRequested = (fn, cb, args...) ->
page._onResourceRequested.apply(page, [fn.toString(), cb].concat(args))
cb page
module.exports =
create: ->
args = []
options = {}
for arg in arguments
switch typeof arg
when 'function' then cb = arg
when 'string' then args.push arg
when 'object' then options = arg
if typeof options.parameters is 'object'
for key, value of options.parameters
args.push '--'+key+'='+value
options.path ?= ''
options.binary ?= options.path+'phantomjs'
options.port ?= 0
options.hostname ?= 'localhost'
options.dnodeOpts ?= {}
ps = null
phantom = null
httpServer = http.createServer()
httpServer.listen options.port, options.hostname
httpServer.on "error", (err) ->
if cb?
cb null, err
else
throw err
httpServer.on 'listening', ->
port = httpServer.address().port
hostname = httpServer.address().address
ps = startPhantomProcess options.binary, port, hostname, args
ps.stdout.on 'data', options.onStdout || (data) ->
console.log "phantom stdout: #{data}"
ps.stderr.on 'data', options.onStderr || (data) ->
module.exports.stderrHandler(data.toString('utf8'))
ps.on 'error', (err) ->
httpServer.close()
if err?.code is 'ENOENT'
console.error "phantomjs-node: You don't have 'phantomjs' installed"
if cb?
cb null, err
else
throw err
# @Description: when the background phantomjs child process exits or
# crashes removes the current dNode phantomjs RPC wrapper from the list of
# phantomjs RPC wrapper
ps.on 'exit', (code, signal) ->
httpServer.close()
if phantom
phantom.onExit?()
phanta = (p for p in phanta when p isnt phantom)
if options.onExit
options.onExit code, signal
else
console.assert not signal?, "signal killed phantomjs: #{signal}"
if code isnt 0
process.exit code
sock = shoe (stream) ->
d = dnode({}, options.dnodeOpts)
d.on 'remote', (_phantom) ->
phantom = _phantom
wrap phantom
phantom.process = ps
phanta.push phantom
cb? phantom, null
d.pipe stream
stream.pipe d
sock.install httpServer, '/dnode'
stderrHandler: (message) ->
NON_ERROR_MESSAGE =
/No such method.*socketSentData|CoreText performance note/
if NON_ERROR_MESSAGE.test message
return # Stupid, stupid QTWebKit
console.warn "phantom stderr: #{message}"

197
node_modules/phantom/phantom.js generated vendored Normal file
View File

@@ -0,0 +1,197 @@
// Generated by CoffeeScript 1.9.3
(function() {
var cleanUp, dnode, http, i, len, onSignalClean, phanta, ref, shoe, signal, spawn, startPhantomProcess, wrap,
slice = [].slice;
dnode = require('dnode');
http = require('http');
shoe = require('shoe');
spawn = require('win-spawn');
phanta = [];
startPhantomProcess = function(binary, port, hostname, args) {
return spawn(binary, args.concat([__dirname + '/shim.js', port, hostname]));
};
cleanUp = function() {
var i, len, phantom, results;
results = [];
for (i = 0, len = phanta.length; i < len; i++) {
phantom = phanta[i];
results.push(phantom.exit());
}
return results;
};
onSignalClean = function(signal) {
return function() {
if (process.listeners(signal).length === 1) {
return process.exit(0);
}
};
};
process.on('exit', cleanUp);
ref = ['SIGINT', 'SIGTERM'];
for (i = 0, len = ref.length; i < len; i++) {
signal = ref[i];
process.on(signal, onSignalClean(signal));
}
wrap = function(ph) {
ph.callback = function(fn) {
return '__phantomCallback__' + fn.toString();
};
ph._createPage = ph.createPage;
return ph.createPage = function(cb) {
return ph._createPage(function(page) {
page._evaluate = page.evaluate;
page.evaluate = function() {
var args, cb, fn;
fn = arguments[0], cb = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
return page._evaluate.apply(page, [fn.toString(), cb].concat(args));
};
page._onResourceRequested = page.onResourceRequested;
page.onResourceRequested = function() {
var args, cb, fn;
fn = arguments[0], cb = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
return page._onResourceRequested.apply(page, [fn.toString(), cb].concat(args));
};
return cb(page);
});
};
};
module.exports = {
create: function() {
var arg, args, cb, httpServer, j, key, len1, options, phantom, ps, ref1, sock, value;
args = [];
options = {};
for (j = 0, len1 = arguments.length; j < len1; j++) {
arg = arguments[j];
switch (typeof arg) {
case 'function':
cb = arg;
break;
case 'string':
args.push(arg);
break;
case 'object':
options = arg;
}
}
if (typeof options.parameters === 'object') {
ref1 = options.parameters;
for (key in ref1) {
value = ref1[key];
args.push('--' + key + '=' + value);
}
}
if (options.path == null) {
options.path = '';
}
if (options.binary == null) {
options.binary = options.path + 'phantomjs';
}
if (options.port == null) {
options.port = 0;
}
if (options.hostname == null) {
options.hostname = 'localhost';
}
if (options.dnodeOpts == null) {
options.dnodeOpts = {};
}
ps = null;
phantom = null;
httpServer = http.createServer();
httpServer.listen(options.port, options.hostname);
httpServer.on("error", function(err) {
if (cb != null) {
return cb(null, err);
} else {
throw err;
}
});
httpServer.on('listening', function() {
var hostname, port;
port = httpServer.address().port;
hostname = httpServer.address().address;
ps = startPhantomProcess(options.binary, port, hostname, args);
ps.stdout.on('data', options.onStdout || function(data) {
return console.log("phantom stdout: " + data);
});
ps.stderr.on('data', options.onStderr || function(data) {
return module.exports.stderrHandler(data.toString('utf8'));
});
ps.on('error', function(err) {
httpServer.close();
if ((err != null ? err.code : void 0) === 'ENOENT') {
console.error("phantomjs-node: You don't have 'phantomjs' installed");
}
if (cb != null) {
return cb(null, err);
} else {
throw err;
}
});
return ps.on('exit', function(code, signal) {
var p;
httpServer.close();
if (phantom) {
if (typeof phantom.onExit === "function") {
phantom.onExit();
}
phanta = (function() {
var k, len2, results;
results = [];
for (k = 0, len2 = phanta.length; k < len2; k++) {
p = phanta[k];
if (p !== phantom) {
results.push(p);
}
}
return results;
})();
}
if (options.onExit) {
return options.onExit(code, signal);
} else {
console.assert(signal == null, "signal killed phantomjs: " + signal);
if (code !== 0) {
return process.exit(code);
}
}
});
});
sock = shoe(function(stream) {
var d;
d = dnode({}, options.dnodeOpts);
d.on('remote', function(_phantom) {
phantom = _phantom;
wrap(phantom);
phantom.process = ps;
phanta.push(phantom);
return typeof cb === "function" ? cb(phantom, null) : void 0;
});
d.pipe(stream);
return stream.pipe(d);
});
return sock.install(httpServer, '/dnode');
},
stderrHandler: function(message) {
var NON_ERROR_MESSAGE;
NON_ERROR_MESSAGE = /No such method.*socketSentData|CoreText performance note/;
if (NON_ERROR_MESSAGE.test(message)) {
return;
}
return console.warn("phantom stderr: " + message);
}
};
}).call(this);

3
node_modules/phantom/pre_shim.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
// Get in there before browserify
var core_require = require;

32
node_modules/phantom/samples/test_phantom.coffee generated vendored Normal file
View File

@@ -0,0 +1,32 @@
# This script demonstrates how phantomjs is used within Nodejs in replacement of
# JSDOM
phantom = require 'phantom'
phantom.create (ph) ->
ph.createPage (page) ->
URL = 'http://www.mdscollections.com/cat_mds_accessories.cfm'
page.open URL, (status) ->
console.log 'Opened site? %s', status
another_funny page, ph
another_funny = (page, ph) ->
# query page for results
page.evaluate ->
# function needs to be within the page evaluate callback
funny = ->
h2Arr = []
results = document.querySelectorAll('.listing_product_name')
for x in [0...results.length]
h2Arr.push(results[x].innerHTML)
return h2Arr
h2Arr = []
pArr = []
h2Arr = funny()
return {
h2: h2Arr
}
, (result) ->
console.log result
ph.exit()

35
node_modules/phantom/samples/test_phantom.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
var phantom = require('phantom');
phantom.create(function(ph) {
ph.createPage(function(page) {
page.open('http://www.mdscollections.com/cat_mds_accessories.cfm',
function(status) {
console.log('Opened site? %s', status);
another_funny(page, ph);
});
});
});
function another_funny(page, ph) {
page.evaluate(function() {
var h2Arr = [];
var pArr = [];
function funny() {
var h2Arr = [];
var results = document.querySelectorAll('.listing_product_name');
var i;
for (i = 0; i < results.length; i++) {
h2Arr.push(results[i].innerHTML);
}
return h2Arr;
}
h2Arr = funny();
return {h2: h2Arr};
},
function(result) {
console.log(result);
ph.exit();
});
}

35
node_modules/phantom/samples/test_phantom_10.coffee generated vendored Normal file
View File

@@ -0,0 +1,35 @@
# Setting cookie header to phantomJS from NodeJS - using Phantom version 0.4.1
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
ph.addCookie 'cookie_name', 'cookie_value', 'localhost', ->
console.log 'Cookie was added'
# Creates on page
ph.createPage (page) ->
page.set('Referer', 'http://google.com')
page.set 'settings.userAgent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.1 (KHTML,
like Gecko) Chrome/21.0.1180.89 Safari/537.1'
page.open "http://localhost:9901/cookie", (status) ->
console.log status
someFunc = (aaa, my_obj) ->
attribute_to_want = aaa
h2Arr = []
results = document.querySelectorAll(attribute_to_want)
for x in [0...results.length]
h2Arr.push(results[x].innerText)
return {
h2: h2Arr
aaa: this.arguments
obj: my_obj
}
finishedFunc = (result) ->
console.log result
ph.exit()
page.evaluate someFunc, finishedFunc, 'div', {wahtt: 111}

30
node_modules/phantom/samples/test_phantom_2.coffee generated vendored Normal file
View File

@@ -0,0 +1,30 @@
# Success: Testing for wikipedia
phantom = require 'phantom'
phantom.create (ph) ->
ph.createPage (page) ->
page.open 'http://en.wikipedia.org/wiki/Main_Page', (status) ->
console.log 'Opened site? %s', status
another_funny page, ph
another_funny = (page, ph) ->
# query page for results
page.evaluate ->
# function needs to be within the page evaluate callback
funny = ->
h2Arr = []
results = document.querySelectorAll('p')
for x in [0...results.length]
h2Arr.push(results[x].innerHTML)
return h2Arr
h2Arr = []
pArr = []
h2Arr = funny()
return {
h2: h2Arr
}
, (result) ->
console.log result
ph.exit()

25
node_modules/phantom/samples/test_phantom_3.coffee generated vendored Normal file
View File

@@ -0,0 +1,25 @@
# Fucked up - on using PhantonJS to get results from pages
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
# Creates on page
ph.createPage (page) ->
page.open "http://wikitravel.org/en/singapore", (status) ->
console.log "opened page? ", status
someFunc = (aaa) ->
attribute_to_want = aaa
h2Arr = []
results = document.querySelectorAll(attribute_to_want)
for x in [0...results.length]
h2Arr.push(results[x].src)
return {
h2: h2Arr
aaa: this.aaa
}
finishedFunc = (result) ->
console.log result
ph.exit()
page.evaluate someFunc, finishedFunc, 'img'

27
node_modules/phantom/samples/test_phantom_4.coffee generated vendored Normal file
View File

@@ -0,0 +1,27 @@
# Success: Working model on using PhantonJS to get results from pages
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
# Creates on page
ph.createPage (page) ->
URL = "http://www.mdscollections.com/cat_mds_accessories.cfm"
page.open URL, (status) ->
console.log "opened page? ", status
someFunc = (aaa) ->
attribute_to_want = aaa
h2Arr = []
results = document.querySelectorAll(attribute_to_want)
for x in [0...results.length]
h2Arr.push(results[x].href)
return {
h2: h2Arr
aaa: this.aaa
sample_dom: results[0]
}
finishedFunc = (result) ->
console.log result
ph.exit()
page.evaluate someFunc, finishedFunc, '.listing_product_name'

26
node_modules/phantom/samples/test_phantom_5.coffee generated vendored Normal file
View File

@@ -0,0 +1,26 @@
# Success: Working model on using PhantonJS to get results from pages
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
# Creates on page
ph.createPage (page) ->
page.open "http://www.deal.com.sg/deals/singapore", (status) ->
console.log "opened page? ", status
someFunc = (aaa, my_obj) ->
attribute_to_want = aaa
h2Arr = []
results = document.querySelectorAll(attribute_to_want)
for x in [0...results.length]
h2Arr.push(results[x].src)
return {
h2: h2Arr
aaa: this.arguments
obj: my_obj
}
finishedFunc = (result) ->
console.log result
ph.exit()
page.evaluate someFunc, finishedFunc, '#deal-main-pic img', {wahtt: 111}

15
node_modules/phantom/samples/test_phantom_6.coffee generated vendored Normal file
View File

@@ -0,0 +1,15 @@
# Test to see what kind of header values can be set
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
# Creates on page
console.log ph
ph.createPage (page) ->
console.log page
page.set('Referer', 'http://google.com')
page.set 'settings.userAgent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.1 (KHTML,
like Gecko) Chrome/21.0.1180.89 Safari/537.1'
page.open "http://localhost:9901", (status) ->
ph.exit()

15
node_modules/phantom/samples/test_phantom_7.coffee generated vendored Normal file
View File

@@ -0,0 +1,15 @@
# Error --- Corner case scenario: page open was called multiple times. One for
# each iframe loaded
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
# Creates on page
ph.createPage (page) ->
page.set('Referer', 'http://google.com')
page.set 'settings.userAgent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.1 (KHTML,
like Gecko) Chrome/21.0.1180.89 Safari/537.1'
page.open "http://www.meetup.com/sgphpug/members/37086072/", (status) ->
console.log 'page open successfully'
ph.exit()

15
node_modules/phantom/samples/test_phantom_8.coffee generated vendored Normal file
View File

@@ -0,0 +1,15 @@
# Corner case scenario: page open was called multiple times. One for each iframe
# loaded
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
# Creates on page
ph.createPage (page) ->
page.set('Referer', 'http://google.com')
page.set 'settings.userAgent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.1 (KHTML,
like Gecko) Chrome/21.0.1180.89 Safari/537.1'
page.open "http://localhost:9901/iframes", (status) ->
console.log 'page open successfully'
ph.exit()

32
node_modules/phantom/samples/test_phantom_9.coffee generated vendored Normal file
View File

@@ -0,0 +1,32 @@
# Corner case scenario: page open was called multiple times. One for each iframe
# loaded
phantom = require 'phantom'
# Creates one process
phantom.create (ph) ->
# Creates on page
ph.createPage (page) ->
page.set('Referer', 'http://google.com')
page.set 'settings.userAgent',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.1 (KHTML,
like Gecko) Chrome/21.0.1180.89 Safari/537.1'
page.open "http://www.facebook.com/VintrySingapore", (status) ->
console.log status
someFunc = (aaa, my_obj) ->
attribute_to_want = aaa
h2Arr = []
results = document.querySelectorAll(attribute_to_want)
for x in [0...results.length]
h2Arr.push(results[x].innerText)
return {
h2: h2Arr
aaa: this.arguments
obj: my_obj
}
finishedFunc = (result) ->
console.log result
ph.exit()
page.evaluate someFunc, finishedFunc, 'div', {wahtt: 111}

162
node_modules/phantom/shim.coffee generated vendored Normal file
View File

@@ -0,0 +1,162 @@
# Require gets overwritten by browserify, so we have to reimplement it from
# scratch - boo :(
webpage = core_require('webpage')
shoe = require('shoe')
dnode = require('dnode')
system = core_require('system')
port = system.args[1]
hostname = system.args[2]
# controlPage = webpage.create()
fnwrap = (target) -> -> target.apply this, arguments
# Descend into objects with dotted keys
descend = (op, obj, key, val) ->
cur = obj
keys = key.split '.'
cur = cur[keys.shift()] while keys.length > 1
cur[keys[0]] = val if op is 'set'
cur[keys[0]]
_transform = (val) ->
if typeof val is "string" and val.indexOf('__phantomCallback__') is 0
val = 'return ' + val.replace('__phantomCallback__', '')
val = phantom.callback(new Function(val)())
return val
transform = (obj) ->
if typeof obj is "string"
_transform(obj)
else if typeof obj is "object"
for key of obj
if typeof obj[key] is "object"
transform(obj[key])
else
obj[key] = _transform(obj[key])
return obj
mkwrap = (src, pass=[], special={}) ->
obj =
set: (key, val, cb=->) ->
#Fnwrap so PhantomJS doesn't segfault when it tries to call the callback
val = fnwrap val if typeof val is "function"
val = transform(val)
cb descend 'set', src, key, val
get: (key, cb) -> cb descend 'get', src, key
for k in pass
do (k) ->
obj[k] = (args...) ->
# This idempotent tomfoolery is required to stop PhantomJS from
# segfaulting
args[i] = fnwrap arg for arg, i in args when typeof arg is 'function'
src[k] args...
for own k of special
obj[k] = special[k]
obj
pageWrap = (page) ->
mkwrap(
page,
['open', 'close', 'includeJs', 'sendEvent', 'release', 'uploadFile',
'goBack', 'goForward', 'reload', 'switchToFrame', 'switchToMainFrame',
'switchToParentFrame', 'switchToFocusedFrame']
# this is here to let the user pass in a function that has access to
# request.abort() and other functions on the request object.
onPageCreated:(cb=(->)) ->
page.onPageCreated = (newpage) ->
cb pageWrap newpage
onConsoleMessage: (fn, cb=(->)) ->
page.onConsoleMessage = ->
fn.apply(this, arguments)
cb()
onError: (fn, cb=(->)) ->
page.onError = ->
fn.apply(this, arguments)
cb()
onResourceRequested: (fn, cb=(->), args...) ->
page.onResourceRequested = ->
# prepare a arguments with the extra args
argumentsWithExtraArgs = [].slice.apply(arguments).concat(args)
# give a name to the anonymouse function so that we can call it
fn = fn.replace /function.*\(/, 'function x('
# the only way we can access the request object is by passing a function
# to this point as a string and expanding it
eval(fn) # :(
# this function has access to request.abort()
x.apply(this, argumentsWithExtraArgs)
# this function does not have access to request.abort()
cb.apply(this, argumentsWithExtraArgs)
injectJs: (js, cb=->) -> cb page.injectJs js
evaluate: (fn, cb=(->), args...) ->
cb page.evaluate.apply(page, [fn].concat(args))
render: (file, opts={}, cb) ->
unless cb?
if typeof opts is 'function'
cb = opts
opts = {}
else
cb = ->
page.render file, opts
cb()
getContent: (cb=->) -> cb page.content
getCookies: (cb=->) -> cb page.cookies
renderBase64: (type, cb=->) -> cb page.renderBase64 type
setHeaders: (headers, cb=->) ->
page.customHeaders = headers
cb()
setContent: (html, url, cb=->) ->
page.onLoadFinished = (status) ->
page.onLoadFinished = null
cb status
page.setContent html, url
setViewportSize: (width, height, cb=->) ->
page.viewportSize = {width:width, height:height}
cb()
setPaperSize: (options, cb=->) ->
page.paperSize = transform(options)
cb()
setZoomFactor: (zoomFactor, cb=->) ->
page.zoomFactor = zoomFactor
cb()
setFileOnPicker: (fileName, cb=->) ->
page.onFilePicker = ->
cb.apply(this, arguments)
fileName
)
_phantom = mkwrap phantom,
['exit'],
injectJs: (js, cb=->) -> cb phantom.injectJs js
getCookies: (cb=->) -> cb(phantom.cookies)
addCookie: (cookie, cb=->) ->
cb(phantom.addCookie(cookie))
clearCookies: (cb=->) -> cb phantom.clearCookies()
createPage: (cb) -> cb pageWrap webpage.create()
setProxy: (host, port, type, user, password, cb=->) ->
cb(phantom.setProxy(host, port, type, user, password))
stream = shoe('http://' + hostname + ':' + port + '/dnode')
d = dnode _phantom
d.pipe stream
stream.pipe d

9770
node_modules/phantom/shim.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

99
node_modules/phantom/test/adv.coffee generated vendored Normal file
View File

@@ -0,0 +1,99 @@
vows = require 'vows'
assert = require 'assert'
express = require 'express'
phantom = require '../phantom'
describe = (name, bat) -> vows.describe(name).addBatch(bat).export(module)
# Make coffeescript not return anything
# This is needed because vows topics do different things if you have a return
# value
t = (fn) ->
->
fn.apply this, arguments
return
app = express()
app.use express.static __dirname
app.get '/', (req, res) ->
res.send """
<html>
<head>
<title>Test page title</title>
</head>
<body>
<img src="/test.gif" />
</body>
</html>
"""
appServer = app.listen()
describe "The phantom module (adv)",
"Can create an instance with --load-images=no":
topic: t ->
phantom.create '--load-images=no', (ph) =>
@callback null, ph
"which, when you open a page":
topic: t (ph) ->
ph.createPage (page) =>
page.open "http://127.0.0.1:#{appServer.address().port}/", (status) =>
setTimeout =>
@callback null, page, status
, 1500
"and check the settings object":
topic: t (page, status) ->
page.get 'settings', (s) =>
@callback null, s
"loadImages isn't set": (s) ->
assert.strictEqual s.loadImages, false
"succeeds": (err, page, status) ->
assert.equal status, 'success'
"and check a test image":
topic: t (page) ->
page.evaluate (-> document.getElementsByTagName('img')[0]), (img) =>
@callback null, img
"it doesn't load": (img) ->
assert.strictEqual img.width, 0, "width should be 0"
assert.strictEqual img.height, 0, "height should be 0"
teardown: (ph) ->
appServer.close()
ph.exit()
"Can create an instance with a custom port and --load-images=yes":
topic: t ->
phantom.create '--load-images=yes', {port: 12301}, (ph) =>
port = 12301
@callback null, port
"which loads on the correct port": (port) ->
assert.equal port, 12301
"Can create an instance with load-images: no in an args object":
topic: t ->
phantom.create {parameters: {'load-images': 'no'}}, (ph) =>
@callback null, ph
"which, when you open a page":
topic: t (ph) ->
ph.createPage (page) =>
page.open "http://127.0.0.1:#{appServer.address().port}/", (status) =>
setTimeout =>
@callback null, page, status
, 1500
"and check the settings object":
topic: t (page, status) ->
page.get 'settings', (s) =>
@callback null, s
"loadImages isn't set": (s) ->
assert.strictEqual s.loadImages, false

57
node_modules/phantom/test/basic.coffee generated vendored Normal file
View File

@@ -0,0 +1,57 @@
vows = require 'vows'
assert = require 'assert'
phantom = require '../phantom'
describe = (name, bat) -> vows.describe(name).addBatch(bat).export(module)
# Make coffeescript not return anything
# This is needed because vows topics do different things if you have a return
# value
t = (fn) ->
->
fn.apply this, arguments
return
describe "The phantom module (basic)",
"Can create an instance":
topic: t ->
phantom.create {port: 12302}, (ph, err) =>
@callback null, [ph, err]
"which is an object": ([ph, err]) ->
assert.isObject ph
"which did not error": ([ph, err]) ->
assert.isNull err
"with a version":
topic: t ([ph, err]) ->
ph.get 'version', (val) =>
@callback null, val
"defined": (ver) ->
assert.notEqual ver, undefined
"an object": (ver) ->
assert.isObject ver
"greater than or equal to 1.3": (ver) ->
assert.ok ver.major >= 1, "major version too low"
if (ver.major is 1)
assert.ok ver.minor >= 3, "minor version too low"
"which can inject Javascript from a file":
topic: t ([ph, err]) ->
ph.injectJs 'test/inject.js', (success) =>
@callback null, success
"and succeed": (success) ->
assert.ok success, "Injection should return true"
"which can create a page":
topic: t ([ph, err]) ->
ph.createPage (page) =>
@callback null, page
"which is an object": (page) ->
assert.isObject page

78
node_modules/phantom/test/callbacks.coffee generated vendored Normal file
View File

@@ -0,0 +1,78 @@
vows = require 'vows'
assert = require 'assert'
phantom = require '../phantom'
Promise = require 'bluebird'
describe = (name, bat) -> vows.describe(name).addBatch(bat).export(module)
# Make coffeescript not return anything
# This is needed because vows topics do different things if you have a return
# value
t = (fn) ->
->
fn.apply this, arguments
return
# Inject an `onExit` callback on `create` to resolve this promise.
exitPromise = new Promise (resolve) ->
wrapCreate = (p) ->
_cached = p.create
wrapped = false
p.create = (args...) ->
for arg, idx in args when typeof arg is 'object'
args[idx]['onExit'] = resolve
wrapped = true
break
args.push {onExit: resolve} unless wrapped is true
_cached.apply phantom, args
wrapCreate phantom
describe "The phantom module (callbacks)",
"Can create an instance":
topic: t ->
phantom.create {port: 12305}, (ph) =>
@callback null, ph
"and can add cookies":
topic: t (ph) ->
ph.addCookie
name: "cookieName"
value: "cookieValue"
path: "/testPath"
domain: "localhost", (status) =>
@callback null, status
"which succeeds": (status) ->
assert.ok status, "addCookie should succeed"
"and, when getCookies is called,":
topic: t (ph) ->
ph.getCookies (cookies) =>
@callback null, cookies
"the cookie is available": (cookies) ->
assert.equal (c for c in cookies when (c) ->
c.name is "cookieName" and
c.value is "cookieValue" and
c.path is "/testPath").length, 1, "cookie must be in phantom.cookies"
"which, when you call exit()":
topic: t (ph) ->
countdown = null
exitPromise.then =>
clearTimeout countdown
@callback null, 'success'
ph.exit()
countdown = setTimeout =>
@callback 'timeout'
, 500
"runs the onExit callback within 500ms": (status) ->
assert.equal status, 'success'

96
node_modules/phantom/test/closing.coffee generated vendored Normal file
View File

@@ -0,0 +1,96 @@
vows = require 'vows'
child_process = require 'child_process'
exec = child_process.exec
spawn = child_process.spawn
assert = require 'assert'
describe = (name, bat) -> vows.describe(name).addBatch(bat).export(module)
t = (fn) ->
->
fn.apply this, arguments
return
program = '''
var phantom = require('./');
process.on('SIGINT', function() {
console.log('SIGINT');
process.exit(0);
});
process.on('SIGTERM', function() {
console.log('SIGTERM');
process.exit(0);
});
process.on('exit', function() {
console.log('EXIT');
});
console.log('Setup');
setTimeout(function() {
console.log('Going out');
}, 1000);
'''
programCbless = '''
var phantom = require('./');
console.log('Setup');
setTimeout(function() {
console.log('Going out');
}, 200);
'''
createTopic = (signal, p) ->
->
that = this
result = ''
co = child_process.exec 'node -e "' + p + '"'
cb = ->
if signal
cb = ->
process.kill co.pid, signal
else
cb = ->
co.stdout.on 'data', (data) ->
result += data
cb() if data.toString().match /^Setup/g
co.stderr.on 'data', (data) ->
result += data
co.on 'exit', (code) ->
that.callback null, [result, co.pid]
return undefined
createExitTest = (expect) ->
(err, [r, pid]) ->
assert.isNull err
assert.deepEqual('Setup\n' + expect, r)
createExitTestCbLess = (expect) ->
(err, [r, pid]) ->
assert.isNull err
assert.deepEqual('Setup\n' + expect, r)
try
process.kill(pid)
assert.fail()
describe "The phantom module",
"SIGINT":
"with callbacks":
topic: createTopic('SIGINT', program)
"exited": createExitTest('SIGINT\nEXIT\n')
"without callbacks":
topic: createTopic('SIGINT', programCbless)
"exited": createExitTestCbLess('')
"SIGTERM":
"with callbacks":
topic: createTopic('SIGTERM', program)
"exited": createExitTest('SIGTERM\nEXIT\n')
"without callbacks":
topic: createTopic('SIGTERM', programCbless)
"exited": createExitTestCbLess('')
"without signals":
"with callbacks":
topic: createTopic(false, program)
"exited": createExitTest('Going out\nEXIT\n')
"without callbacks":
topic: createTopic(false, programCbless)
"exited": createExitTestCbLess('Going out\n')

53
node_modules/phantom/test/error.coffee generated vendored Normal file
View File

@@ -0,0 +1,53 @@
vows = require 'vows'
assert = require 'assert'
phantom = require '../phantom'
describe = (name, bat) -> vows.describe(name).addBatch(bat).export(module)
# Make coffeescript not return anything
# This is needed because vows topics do different things if you have a return
# value
t = (fn) ->
->
fn.apply this, arguments
return
describe "The phantom module (error behavior)",
"Can try to spawn instance at nonexistent path":
topic: t ->
phantom.create {port: 12311, path: "./test/doesn't-exist"}, (ph, err) =>
@callback null, [ph, err]
"which is null": ([ph, err]) ->
assert.isNull ph
"which returned an error": ([ph, err]) ->
assert.isObject err
"with an error code of ENOENT": ([ph, err]) ->
assert.strictEqual err?.code, "ENOENT"
"Can try to spawn two instances on the same port":
topic: t ->
phantom.create {port: 12312}, (ph, err) =>
@callback null, [ph, err]
"where the first succeeds": ([ph, err]) ->
assert.isObject ph
"and does not error": ([ph, err]) ->
assert.isNull err
"but, when the second is run,":
topic: t ->
phantom.create {port: 12312}, (ph2, err2) =>
@callback null, [ph2, err2]
"it fails": ([ph2, err2]) ->
assert.isNull ph2
"and it errors": ([ph2, err2]) ->
assert.isObject err2
"with error code EADDRINUSE": ([ph2, err2]) ->
assert.equal err2.code, "EADDRINUSE"

93
node_modules/phantom/test/frames.coffee generated vendored Normal file
View File

@@ -0,0 +1,93 @@
vows = require 'vows'
assert = require 'assert'
express = require 'express'
phantom = require '../phantom'
describe = (name, bat) -> vows.describe(name).addBatch(bat).export(module)
# Make coffeescript not return anything
# This is needed because vows topics do different things if you have a return
# value
t = (fn) ->
->
fn.apply this, arguments
return
app = express()
app.use express.static __dirname
app.get '/', (req, res) ->
res.send """
<html>
<head>
<title>Test page title</title>
</head>
<body>
<iframe src="/inner" name="inner"></iframe>
</body>
</html>
"""
app.get '/inner', (req, res) ->
res.send """
<html>
<head>
<title>Inner page title</title>
</head>
<body>
</body>
</html>
"""
appServer = app.listen()
describe "The phantom module (frames)",
"Can switch to inner frame on the page":
topic: t ->
phantom.create (ph) =>
@callback null, ph
"which, when you open a page":
topic: t (ph) ->
ph.createPage (page) =>
page.open "http://127.0.0.1:#{appServer.address().port}/", (status) =>
setTimeout =>
@callback null, page, status
, 1500
"and extract the inner frame's title":
topic: t (page, status) ->
page.switchToFrame("inner")
page.evaluate (-> document.title), (title) =>
@callback null, title
"it is correct": (title) ->
assert.equal title, "Inner page title"
"and switch back to parent frame and extract the title":
topic: t (page, status) ->
page.switchToParentFrame()
page.evaluate (-> document.title), (title) =>
@callback null, title
"it is correct": (title) ->
assert.equal title, "Test page title"
"and switch from inner frame to main frame and extract the title":
topic: t (page, status) ->
page.switchToFrame("inner")
page.switchToMainFrame()
page.evaluate (-> document.title), (title) =>
@callback null, title
"it is correct": (title) ->
assert.equal title, "Test page title"
"succeeds": (err, page, status) ->
assert.equal status, 'success'
teardown: (ph) ->
appServer.close()
ph.exit()

2
node_modules/phantom/test/inject.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
//This isn't really a very good test
//(function(){var foo = 3;})();

207
node_modules/phantom/test/page.coffee generated vendored Normal file
View File

@@ -0,0 +1,207 @@
vows = require 'vows'
assert = require 'assert'
phantom = require '../phantom'
express = require 'express'
temp = require 'temp'
path = require 'path'
fs = require 'fs'
describe = (name, bat) -> vows.describe(name).addBatch(bat).export(module)
# Make coffeescript not return anything
# This is needed because vows topics do different things if you have a return
# value
t = (fn) ->
->
fn.apply this, arguments
return
app = express()
app.get '/', (req, res) ->
res.send """
<html>
<head>
<title>Test page title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<div id="somediv">
<div class="anotherdiv">Some page content</div>
</div>
<button class="clickme" style="position: absolute; top: 123px; left: 123px; width: 20px; height; 20px" onclick="window.i_got_clicked = true;" />
<input type='file' id='upfile' name='upfile'>
</body>
</html>
"""
appServer = app.listen()
describe "Pages",
"A Phantom page":
topic: t ->
phantom.create {port: 12303}, (ph) =>
ph.createPage (page) =>
@callback null, page, ph
"can open a URL on localhost":
topic: t (page) ->
page.open "http://127.0.0.1:#{appServer.address().port}/", (status) =>
@callback null, page, status
"and succeed": (err, page, status) ->
assert.equal status, "success"
"and the page, once it loads,":
topic: t (page, status) ->
setTimeout =>
@callback null, page
, 1500
"has a title":
topic: t (page) ->
page.evaluate (-> document.title), (title) =>
@callback null, title
"which is correct": (title) ->
assert.equal title, "Test page title"
"has cookies":
topic: t (page) ->
page.getCookies (cookies) =>
@callback null, cookies
"which works correctly": (cookies) ->
assert.ok cookies, "cookies should not be empty"
"can inject Javascript from a file":
topic: t (page) ->
page.injectJs 'test/inject.js', (success) =>
@callback null, success
"and succeed": (success) ->
assert.ok success, "Injection should return true"
"can evaluate DOM nodes":
topic: t (page) ->
page.evaluate (-> document.getElementById('somediv')), (node) =>
@callback null, node
"which match": (node) ->
assert.equal node.tagName, 'DIV'
assert.equal node.id, 'somediv'
"can evaluate scripts defined in the header":
topic: t (page) ->
page.evaluate (-> $('#somediv').html()), (html) =>
@callback null, html
"which return the correct result": (html) ->
html = html.replace(/\s\s+/g, "")
assert.equal html, '<div class="anotherdiv">Some page content</div>'
"can set a nested property":
topic: t (page) ->
page.set 'settings.loadPlugins', true, (oldVal) =>
@callback null, page, oldVal
"and get it again":
topic: t (page, oldVal) ->
page.get 'settings.loadPlugins', (val) =>
@callback null, oldVal, val
"and they match": (err, oldVal, val) ->
assert.equal oldVal, val
"can simulate clicks on page locations":
topic: t (page) ->
page.sendEvent 'click', 133, 133
page.evaluate (-> window.i_got_clicked), (clicked) =>
@callback null, clicked
"and have those clicks register": (clicked) ->
assert.ok clicked
###
"can register an onAlert handler":
topic: t (page) ->
page.set 'onAlert', (msg) =>
@callback null, msg
page.evaluate (-> alert "Hello, world!")
"which works correctly": (msg) ->
assert.equal msg, "Hello, world!"
###
###
"can register an onConsoleMessage handler":
topic: t (page) ->
page.set 'onConsoleMessage', (msg) =>
@callback null, msg
page.evaluate (-> console.log "Hello, world!")
"which works correctly": (msg) ->
assert.equal msg, "Hello, world!"
###
"can register an onConsoleMessage handler":
topic: t (page) ->
page.onConsoleMessage (msg) =>
@callback null, msg
page.evaluate (-> console.log "Hello, world!")
"which works correctly": (msg) ->
assert.equal msg, "Hello, world!"
"can register an onError handler":
topic: t (page) ->
page.onError (msg) =>
@callback null, msg
page.evaluate (-> eval "syntaxerror[")
"which works correctly": (msg) ->
assert.equal msg, "SyntaxError: Parse error"
"can render the page to a file":
topic: t (page) ->
fileName = temp.path suffix: '.png'
page.render fileName, =>
@callback null, fileName
"which is created": (fileName) ->
assert.ok fs.existsSync(fileName), "rendered image should exist"
teardown: (fileName) ->
fs.unlink fileName
# handles clicking on 'input[type=file]'. Based on
# https://github.com/ariya/phantomjs/blob/eddb0db/test/webpage-spec.js
"can set the file to upload when the file picker is invoked":
topic: t (page) ->
fileToUpload = (
if /^win/.test(process.platform)
'C:\\Windows\\System32\\drivers\\etc\\hosts'
else
'/etc/hosts'
)
page.setFileOnPicker fileToUpload
page.evaluate (->
upFile = document.querySelector('input[name=upfile]')
ev = document.createEvent('MouseEvents')
ev.initEvent('click', true, true)
upFile.dispatchEvent(ev)
), => @callback null, page, fileToUpload
"which":
topic: t (page, fileToUpload) ->
page.evaluate (->
document.querySelector('input[name=upfile]').files[0].name
), (fileName) =>
@callback null, fileName, fileToUpload
"matches with the passed filename": (err, fileName, fileToUpload) ->
assert.ok fileToUpload.indexOf(fileName) > -1
teardown: (page, ph) ->
appServer.close()
ph.exit()

BIN
node_modules/phantom/test/test.gif generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB