I'm doing a Google Chrome extension that interacts with Gmail chat and can send the same message to all open chat, the functional part is done, but I can not send the keydown
event to the textareas.
What I am doing is using a page_action
to show the extension icon when the user visit Gmail. When the user click the extension icon, it is going to prompt a popup with a textarea, when the user have opened chat and write something to the textarea and then press Enter key, the textarea of each opened chat are going to fill the same message and suppused to fire keydown
event.
Here is the essential code:
popup.js
chrome.tabs.executeScript(null, {file: 'send.js'}, function () {
// 'message' is the textarea inside the popup.html
var message = document.getElementById('message');
message.onkeydown = function (e) {
if (13 == e.keyCode) {
chrome.tabs.executeScript(null, {code: 'send("' + message.value + '");'}, function () {
message.value = '';
});
return false;
}
};
});
send.js
function send(message) {
if (message) {
for (var i = 0, textareas = document.getElementsByTagName("TEXTAREA"), length = textareas.length; i < length; ++i) {
textarea = textareas[i];
textarea.value = message;
var evt = document.createEvent('KeyboardEvent');
evt.initKeyboardEvent('keydown', true, true, null, false, false, false, false, 13, 13);
Object.defineProperty(evt, 'keyCode', {
get : function() {
return 13;
}
});
Object.defineProperty(evt, 'which', {
get : function() {
return 13;
}
});
Object.defineProperty(evt, 'keyIdentifier', {
get : function() {
return 'Enter';
}
});
Object.defineProperty(evt, 'shiftKey', {
get : function() {
return false;
}
});
textarea.dispatchEvent(evt);
}
}
}
The code did not have problem filling the textareas, so all textareas is reconized, but the keydown
event did not fire after the script filled textareas. The strange part, is when I tried the send.js code into the Google Chrome console, the keydown
event fire normally and the messages were send, but I can't do samething with the extension.
So, how can I fire the keydown
event into the extension?