Passing variable from this.evaluate to casper.then
casperjs, javascript, phantomjs, scope, webkit
Solution
The problem is that Google seems to be serving different versions when browsed with different user agents, for some very obscure reason. I'm suspecting heavy browser/user agent sniffing.
In our case, playing with `Casper.debugHTML()` shows that the code doesn't contain the button matching the `#gbqfsa` selector (while Chrome shows one); instead a standard submit `<input name="btnG">` is there.
So here's your script using the actual selector for the button:
var casper = require("casper").create();
var buttonText;
casper.start("http://google.com/", function() {
buttonText = this.evaluate(function () {
var myTxt = document.querySelector('input[name="btnG"]').getAttribute('value');
__utils__.echo('1: ' + myTxt);
return myTxt;
});
this.echo('2: ' + buttonText);
});
casper.run();
Just an idea, try to use `Casper.userAgent()` to set the UA to something more common, eg. a recent chrome version.
PS: also notice the use of `__utils__.echo()` to print stuff directly from within `evaluate()`.
Edit: It works by setting a common UA:
casper.start();
casper.userAgent("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.204 Safari/534.16");
casper.thenOpen('http://google.com/', function() {
this.test.assertExists('#gbqfsa'); // PASS
});
casper.run(function() {
this.test.done();
});
Problem
I must have lost my mind on this but why it didn't print out `"1: Google Search"` and `"2: Google Search"`? Basically: how do I get a variable within this.evaluate and use it in the rest of casper.js scope? ``` var casper = require("casper").create(); var buttonText; casper.start("http://google.com"); casper.then(function() { buttonText = this.evaluate(function () { var myTxt = document.querySelector('#gbqfsa').innerText; console.log('1: ' + myTxt); return myTxt; }); }); casper.then(function() { this.echo('2: ' + buttonText); }); casper.on('remote.message', function(msg) { this.echo('remote message caught: ' + msg); }); casper.run(); ``` I am using these libraries here: https://github.com/ariya/phantomjs http://casperjs.org/index.html