This was my original question and was taken to this question very kindly by @rsanchez and @Xan. I would have loved to further ask on the link that they provided for me, but I don't have enough reputation to comment and so I'm having to make a new question here.
So my problem is that I'm developing a chrome extension in which I would like to get message from my server using Pusher and upon this message arriving, I would like to open up the appropriate chat and put the message I recieved from the server onto a textarea with id messageInput
and fire the keypress
event defined in the page's script.
I now understand that doing
var $message = $("#messageInput");
var e = $.Event("keypress", {keyCode: 13}); //keypress defined for enter
$message.text(myMessage);
$message.trigger(e);
won't work because it doesn't really call the real keypress
event of the page's script.
And because I'm using a pusher module, I would like to not do the injection method since from what I understand, it's not possible to pass message from my content script to the injected script.
So I would like to use the KeyboardEvent
method as suggested by the question that @rsanchez and @Xan pointed out. So I've tried it in the console first, only to see the returned value "true" with no events occurring at all. So how should I implement the following into my code?
content_script.js
...
channel.bind('returned_message', function(data) {
// returned_message is the message from server
var $message = $("#messageInput");
var e = $.Event("keypress", {keyCode: 13});
$message.text(data.message);
console.log($message.text());
$message.trigger(e);
});
here's what I figure I should implement instead of $.Event
:
var e = new KeyboardEvent('keypress');
e.code = 13;
document.querySelector("#messageInput").dispatchEvent(e);
Thank you in advance.
EDIT
Here's the excerpt of the code that I found from the page's native script:
...
$msgInput.keypress(function(e) {
if(e.keyCode == 13 && !e.shiftKey) {
var msg = $msgInput.val().trim();
if(msg.length > 0) {
sendMsg(msg);
$msgInput.val('');
}
e.preventDefault();
}
});
...
where at the beginning of the script $msgInput
was defined as $msgInput = $("#messageInput")
.