Casper.js:在ExtJs输入框中按下“Enter”键

5

我在页面上有一个ExtJs文本字段。我在casper.js中填充它的一些值,这很好用。
然后,我想将焦点放在此字段上并按Enter键,因为周围没有<form>可提交。

我尝试过的是:

casper.then(function() {
  // the text field is filled with the string
  this.sendKeys('#searchfield', 'some text');

  this.evaluate(function() {
    // this does not put the field in focus        
    document.querySelector('#searchfield').focus();

    // so 'pressing' enter has no effect at all
    var evt = document.createEvent('KeyboardEvent');
    evt.initKeyboardEvent('keypress', true, true, window, 0, 0, 0, 0, 0, 13);
    document.dispatchEvent(evt);
  });
});

你有什么想法来完成这个任务吗?
2个回答

1

你的代码

evt.initKeyboardEvent('keypress', true, true, window, 0, 0, 0, 0, 0, 13);

看第四个参数,我猜它应该是触发元素。这里应该是document.querySelector('#searchfield')

一个提示:在casper evaluate中,最后返回true,如果evaluate中有任何错误,你将得到null。

var result = this.evaluate(function(){ /*code is here*/ return true;})

检查结果,如果成功。

谢谢您的回复。第四个参数是 viewArg,通常只是 window 对象。不幸的是,将其更改为我的元素并没有改变任何东西。它只是没有被按下。 - dan-lee
2
我现在只使用\n来发送回车键,请尝试这个this.sendKeys('#searchfield', 'some text\n'); - Flying Fisher

0

两个建议:

第一个:尝试使用this.thenEvaluate而不是evaluate。需要使用then来确保异步序列正确工作。

第二个:这可能是客户端js问题。在浏览器中,您可以检查js控制台,但在这里不行。因此,您应该添加一些调试助手。

casper.on('log.message', function(msg){
  console.log(msg);
}

这将把您的远程控制台消息传送到您的控制台。现在,您可以使用console.log()调试远程上下文,并查看它在哪里(如果)出错。

您还应该设置verbose=truelogLevel="debug"以使其正常工作。

祝你好运!


感谢您的回答,很抱歉我回复晚了。我发现问题不在Casper层面上,而是甚至在正常的浏览器窗口(Chrome)中也存在。 - dan-lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接