I'm working on a browser extension (google chrome and firefox) which uses content script to change a textarea value. I'm working with this script:
On google chrome I use this script :
function print(msg, textarea){
textarea.focus();
textarea.click();
textarea.value = '';
for(var i=0; i<msg.length;i++){
var e = document.createEvent('KeyboardEvent');
e.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 0, msg.charCodeAt(i));
textarea.dispatchEvent(e);
textarea.value += msg[i];
}
}
On some websites using AJAX the value of the textarea is correctly updated but for some reasons when I submit the form, the old textarea content is posted instead. If I manually press one key, the problem is solved.
I can't understand where the problem is. I tried $(textarea).keydown().keypress().keyup().change() or .blur() with jQuery but it didn't help.
Wladimir is right, the issue is often about a hidden field and the keyup event. The triggering order is the key. I believe a correct way is :
for(var i=0; i<msg.length;i++){
var e = document.createEvent('KeyboardEvent');
e.initKeyboardEvent("keydown", true, true, null, false, false, false, false, 0, msg.charCodeAt(i));
textarea.dispatchEvent(e);
var e = document.createEvent('KeyboardEvent');
e.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 0, msg.charCodeAt(i));
textarea.dispatchEvent(e);
textarea.value += msg[i];
var e = document.createEvent('KeyboardEvent');
e.initKeyboardEvent("keyup", true, true, null, false, false, false, false, 0, msg.charCodeAt(i));
textarea.dispatchEvent(e);
}
It worked on firefox and google chrome (but firefox uses initKeyEvent instead of initKeyboardEvent)