在下面的示例中,我试图在using evaluate中声明一个名为foo
的全局变量。然后使用网页上的脚本输出它。但是错误消息表明该变量尚未定义。
<html>
<head>
<meta charser="utf-8">
<title> Page title </title>
</head>
<body>
<script>
window.onload = function() {
console.log('started webpage script');
console.log(foo);
};
</script>
</body>
</html>
var casper = require('casper').create({
verbose : true,
logLevel : "debug"
});
casper.start('http://localhost:8080');
casper.on('page.error', function(err) {
this.echo(err, 'ERROR');
});
casper.on('remote.message', function(msg) {
this.echo(msg);
});
casper.on('run.start', function() {
casper.evaluate(function() {
console.log('Running evaluate script');
window.foo = "Hello world!";
});
});
casper.run();
[info] [phantom] Starting...
[info] [phantom] Running suite: 2 steps
[debug] [phantom] Successfully injected Casper client-side utilities
Running evaluate script
[debug] [phantom] opening url: http://localhost:8080/, HTTP GET
[debug] [phantom] Navigation requested: url=http://localhost:8080/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "http://localhost:8080/"
started webpage script
ReferenceError: Can't find variable: foo
[debug] [phantom] Successfully injected Casper client-side utilities
[debug] [phantom] start page is loaded
[info] [phantom] Done 2 steps in 65ms
答案 0 :(得分:0)
我需要在page.initialize
casper.on('page.initialize', function() {
casper.evaluate(function() {
console.log('Running evaluate script');
window.foo = "Hello world!";
});
});