簡體   English   中英

console.log在CasperJS'使用setTimeout進行評估時不起作用

[英]console.log doesn't work in CasperJS' evaluate with setTimeout

為什么當我在evaluate使用console.log時,它的工作原理是:

casper.then(function() {
  this.evaluate( function() {
    console.log('hello'); 
  });
});

但這不起作用:

casper.then(function() {
  this.evaluate( function() {
    setTimeout( function() {console.log('hello');}, 1000);
  });
});

因為你正在混合casperjs和遠程頁面環境。 evaluate函數將在遠程頁面env中執行代碼,因此console.log調用不會輸出任何內容。

如果要捕獲遠程 console.log調用,請偵聽remote.message事件:

casper.on('remote.message', function(msg) {
    this.echo('remote message caught: ' + msg);
})

順便說一句, 事件的文檔非常詳盡,以及評估的 文檔

@ NiKo的答案很關鍵。

我還建議添加以下內容,因為如果出現錯誤,您甚至可能無法打印出一個console.log()消息,而最終會沉默。

casper.on( 'page.error', function (msg, trace) {
    this.echo( 'Error: ' + msg, 'ERROR' );
});

CasperJS包含ClientUtils ,可以從遠程頁面使用它輕松登錄到casper腳本的控制台:

__utils__.echo('This message is logged from the remote page to the CasperJS console');

在@ odigity的答案的基礎上,這使得casperjs死於更熟悉的錯誤/堆棧跟蹤:

var util = require('util');

casper.on('page.error', function exitWithError(msg, stack) {
    stack = stack.reduce(function (accum, frame) {
        return accum + util.format('\tat %s (%s:%d)\n',
            frame.function || '<anonymous>',
            frame.file,
            frame.line
        );
    }, '');
    this.die(['Client-side error', msg, stack].join('\n'), 1);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM