A little background... I'm a little new to javascript, and to phantom.js, so I don't know if this is a javascript or phantom.js bug (feature?).
The following completes successfully (sorry for the missing phantom.exit(), you'll just have to ctrl+c once you are done):
var page = require('webpage').create();
var comment = "Hello World";
page.viewportSize = { width: 800, height: 600 };
page.open("http://www.google.com", function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
page.includeJs('http://code.jquery.com/jquery-latest.min.js', function() {
console.log("1: ", comment);
}, comment);
var foo = page.evaluate(function() {
return arguments[0];
}, comment);
console.log("2: ", foo);
}
});
This works:
page.includeJs('http://code.jquery.com/jquery-latest.min.js', function() {
console.log("1: ", comment);
}, comment);
Output: 1: Hello World
But not:
page.includeJs('http://code.jquery.com/jquery-latest.min.js', function(c) {
console.log("1: ", c);
}, comment);
Output: 1: http://code.jquery.com/jquery-latest.min.js
And not:
page.includeJs('http://code.jquery.com/jquery-latest.min.js', function() {
console.log("1: ", arguments[0]);
}, comment);
Output: 1: http://code.jquery.com/jquery-latest.min.js
Looking at the 2nd piece, this works:
var foo = page.evaluate(function() {
return arguments[0];
}, comment);
console.log("2: ", foo);
Output: 2: Hello World
And this:
var foo = page.evaluate(function(c) {
return c;
}, comment);
console.log("2: ", foo);
Output: 2: Hello World
But not this:
var foo = page.evaluate(function() {
return comment;
}, comment);
console.log("2: ", foo);
Output:
ReferenceError: Can't find variable: comment
phantomjs://webpage.evaluate():2
phantomjs://webpage.evaluate():3
phantomjs://webpage.evaluate():3
2: null
The good news is, I know what works and what doesn't, but how about a little consistency?
Why the difference between includeJs
and evaluate
?
Which is the proper way to pass arguments to an anonymous function?