nightmare.js 中的 Type 方法将文本分配给输入控件的 value 属性。由于此实现 keydown,keypress 事件不会在您尝试抓取的页面上触发。有什么方法可以在“输入”后发送 keydown 事件吗?
编辑 1-
这是一个使用 jQuery 发送事件的示例,它也不起作用 -
var Nightmare = require('nightmare');
var vo = require('vo');
var nightmare = Nightmare();
vo(run)(function(err, result) {
if (err) throw err;
});
function *run() {
var title = yield nightmare
.goto('http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes')
.type('#txtChar','\n')
.evaluate(function() {
var e = $.Event( "keypress", { which: 13 } );
$('#txtChar').trigger(e);
return "Key you pressed is : " + $('#txtChar').val();
});
yield nightmare.pdf('type.pdf');
setTimeout(function () {
console.log( ' ' + title);
nightmare.end();
process.exit();
},2000);
}
编辑2-
使用相当于键的 unicode 作为类型方法的参数会以某种方式调用附加事件,不完全确定这个黑客是如何工作的,但它确实有效!
这是工作示例-
var Nightmare = require('nightmare');
var vo = require('vo');
var nightmare = Nightmare();
vo(run)(function(err, result) {
if (err) throw err;
});
function *run() {
var title = yield nightmare
.goto('http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes')
.type('#txtChar','1') //so we have focus on textbox
.type('document', '\u000d')
.evaluate(function() {
return "Key you pressed is : " + $('#txtChar').val();
});
yield nightmare.pdf('type.pdf');
setTimeout(function () {
console.log( ' ' + title);
nightmare.end();
process.exit();
},2000);
}
最佳答案
您可以使用纯 JS 或 jQuery 评估页面并发送 keydown 事件,jQuery 是最简单的方法,但它最需要注入(inject)。
使用 jQuery:
.inject('js', '/jquery-2.1.4.min.js')
.evaluate(function () {
var e = $.Event( "keypress", { which: 13 } );
$('#yourInput').trigger(e);
});
编辑: 看起来 Nightmare 支持触发关键事件。看看https://github.com/segmentio/nightmare/issues/244和 https://github.com/segmentio/nightmare/issues/147 .
编辑2:不,应该是.type('document', '\u000d')
。得到了错误的 unicode 字符。
关于node.js - 在 Nightmare.js 中发送 keydown、keypress 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34962253/