最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS Testing: Trigger jQuery keypress event from CasperJS and PhanthomJS - Stack Overflow

programmeradmin3浏览0评论

my webpage has a listener to the enter key press event. I am trying to run the casperjs code below to trigger this event, but without success.

Although no error is prompted out, the (evaluate) function returns true and the code works fine from my chrome console, the function result, that should be sending a request to the server is never happening

casper.then(function(){
    var result = this.evaluate(function(term){
        var search_form_id = "#search-form";
        $(search_form_id).val(term);

        jQuery(search_form_id).trigger(jQuery.Event('keypress', {which: 13, keyCode: 13}));

        return true;
    }, 'Techcrunch');
    console.log(result);
});

Is that any issue regarding PhantomJS and jQuery events?

my webpage has a listener to the enter key press event. I am trying to run the casperjs code below to trigger this event, but without success.

Although no error is prompted out, the (evaluate) function returns true and the code works fine from my chrome console, the function result, that should be sending a request to the server is never happening

casper.then(function(){
    var result = this.evaluate(function(term){
        var search_form_id = "#search-form";
        $(search_form_id).val(term);

        jQuery(search_form_id).trigger(jQuery.Event('keypress', {which: 13, keyCode: 13}));

        return true;
    }, 'Techcrunch');
    console.log(result);
});

Is that any issue regarding PhantomJS and jQuery events?

Share Improve this question asked May 12, 2014 at 12:11 marcelosalloummarcelosalloum 3,5414 gold badges42 silver badges65 bronze badges 1
  • 1 I tried something similar (with 'enter' keypress, 'Down' too) without success. It might be possible it's a phantom issue. – Fanch Commented May 12, 2014 at 12:27
Add a ment  | 

1 Answer 1

Reset to default 9

It looks like, you can't trigger the keypress event using jQuery. There is a workaround using the underlying casper.page.sendEvent function. Though it is necessary to focus on the element, where the keypress will be triggered. In the following example I use the keepFocus option of the sendKeys function.

var casper = require('casper').create();
casper.start("https://duckduckgo./");
casper.then(function() {
    this.sendKeys("#search_form_homepage input[name=q]", "casperjs", { keepFocus: true });
    this.capture("typed.png");
    this.page.sendEvent("keypress", this.page.event.key.Enter);
});

casper.waitForSelector("#links_wrapper");

casper.then(function() {
    this.capture("searched.png");
});

casper.run();
发布评论

评论列表(0)

  1. 暂无评论