javascript - How to call an external function from within casper.start or casper.thenOpen -


i trying split following code such callback function stored in own file.

var casper = require('casper').create(); casper.start("http://www.google.com/", function() {     this.echo(this.gettitle()); }); casper.run(); // "returns google" 

following this example, define function in separate file called "getpagetitle.js";

function getpagetitle(casper) {     casper.echo(casper.gettitle()); } exports.getpagetitle = getpagetitle; 

and call function in file called "main.js" passing casperjs object function directly;

var casper = require('casper').create(); var casperfunctions = require('./getpagetitle.js'); casper.start("http://www.google.com/", casperfunctions.getpagetitle(casper)); # error: caspererror: casper not started, can't execute `gettitle()`                   

further, if replace last line in above thenopen() call;

casper.start(); casper.thenopen("http://www.google.com/", casperfunctions.getpagetitle(casper)); 

the above code not throw errors; casperjs able navigate website, page title "google" not returned.

could please shed light on why doesn't behave expect. seems natural way modularize functions casperjs call once pages loading, missing here?

the execution of casperjs asynchronous. start() , then*() , wait*() functions asynchronous step functions. means you're on page inside of such step.

when @ getpagetitle() , how called, should notice you're not passing step function casper.start(), instead you're calling getpagetitle(). @ time, execution hasn't begun, because scheduled steps begin executing run() called. calling getpagetitle(), you're trying access title of about:blank blank.

first version:

function getpagetitle(casper) {     return function(){         casper.echo(casper.gettitle());     }; } 

now you're passing step function start() evaluated asynchronously.

second version:

keep in mind can use this inside of step function refer casper. better way this, because don't need pass reference explicitly:

function getpagetitle() {     return function(){         this.echo(this.gettitle());     }; } 

and call this:

casper.start("http://www.google.com/", casperfunctions.getpagetitle()); 

third version:

if function doesn't need arguments, don't need wrapper function. can pass directly:

function getpagetitle() {     this.echo(this.gettitle()); } 

and call this:

casper.start("http://www.google.com/", casperfunctions.getpagetitle); 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -