Reputation: 557
As a simple way to test if javascript is executing correctly from CasperJS, I'm trying to have an alert box in javascript pop up on the page. My end goal is running more complex javascript functions, but for right now I just wanted to start with something easy (i.e. if there is a native CasperJS alert box function, I don't want to use it because I want to get javascript working).
var casper = require("casper").create();
casper.start("http://www.google.com", function() {
});
casper.thenEvaluate(function() {
alert('hi');
});
casper.then(function(){
this.wait(500, function() {
this.echo("I've waited for 500 milliseconds");
});
this.capture('google.png', {
top: 0,
left: 0,
width: 1500,
height: 1000
});
});
casper.run(function() {
this.echo(this.getTitle()); // Google
this.exit();
});
When I run this script, I do visit http://www.google.com (as evidence from the screenshot) but no alert box shows up.
Does anyone know how to run javascript from CasperJS?
Thanks!
Upvotes: 0
Views: 9199
Reputation: 16838
As to why alert('hi')
won't be seen, this link gives a good explanation. Basically, casperjs/phantomjs is a headless browser and hence can't have a window or dialogs.
But inject your scripts into a remote page and execute them you can: here's how in Casperjs docs.
Here's your script slightly modified (note that jquery.js here is supposed to be in the local filesystem, in the same folder from which you issue your command to launch CasperJS in the console):
var casper = require("casper").create({
clientScripts: ["jquery.js"]
});
casper.start("http://www.google.com/ncr");
casper.then(function(){
this.evaluate(function() {
$("input[name='q']").val("CasperJS execute javascript on remote page");
});
});
casper.then(function(){
this.capture('google.png', {
top: 0,
left: 0,
width: 1500,
height: 1000
});
});
casper.run(function() {
this.echo(this.getTitle()); // Google
this.exit();
});
Upvotes: 2