Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
791 views
in Technique[技术] by (71.8m points)

javascript, simulate keyboard events, work on chrome(webkit)

in FF, i've used this code:


if (keyCount == lineLimit) {
    // method in FF, no Chrome
    var mock = document.createEvent("KeyboardEvent"); // or KeysEvent
    mock.initKeyEvent("keypress",true,true,null,false,false,false,false,14,0);
    var x = document.getElementById('InputCategory');
    // rise height before Enter
    $(this).height(div_height + font_height + offset_height);
    // mock Enter
    x.dispatchEvent(mock);
    // init keyCount
    keyCount = 0;
}

it works, but could not be effective on webkit-based browsers like chrome.

so i asked google and found keyboard event is one of the DOM Level 3 events,here is an aticle: http://www.w3.org/TR/DOM-Level-3-Events/

then i knew /* initKeyboardEvent / is not supported on chrome & safari, / initUIEvent */ i've tried, it didn't work also.

Do virtual keyboard events reall can be simulated on chrome ? plesase help me :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This works, but it's not generating a keypress-event, rather a text-insert event.

var te = document.createEvent('TextEvent');
te.initTextEvent('textInput', true, true, window, 'test');
<element>.dispatchEvent(te);

That inserts the word 'test' at the end of the input (in your case you'd probably replace that by .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...