0

I'm trying to write an extension for Opera that automatically sends specific chat messages. (Commands, to be exact.) For that, I want to enter the message into the textarea, simulate a button click to send the message and read the reply I get.

I've been trying to use the Element.click() function of JavaScript to simulate the click, but it doesn't work. My code goes something like this:

document.getElementsByClassName("text-area")[0].value = "test";
document.getElementsByClassName("send-chat-button")[0].click();

The textarea gets filled in with the value I want, but it doesn't click the button. I am also not getting any output on the console. I'd be glad about any help I can get.

Regards, Kileraptor1

UPDATE: You were right, the button does not have an OnClick event like I thought it had. I'm honestly not sure how it submits a message. Since I am writing a plugin for a website I do not own, I can not edit the source or anything.

Kileraptor1
  • 11
  • 1
  • 7
  • Unless you're using jQuery, JavaScript uses `onclick` not `click()`. – Henry A. Mar 30 '16 at 18:09
  • @Henry I don't want to trigger a function by pressing the button, I want to simulate a button click using JavaScript. – Kileraptor1 Mar 30 '16 at 18:13
  • Maybe you have to use keypress for simulate when you press enter into the textarea, at this point, add with .addClass in jquery the styles simulate to the button. You can do this only with jquery. – Fernando Torres Mar 30 '16 at 18:14
  • Have you actually got a handler for the click event assigned to the button? – Stuart Mar 30 '16 at 18:16
  • @Kileraptor1 You need an event handler attached to the element in order to work with it, see my answer. – Henry A. Mar 30 '16 at 18:22

1 Answers1

0

The easiest way would be with the trigger() function in jQuery:

$(".send-chat-button:first").click(function()
{
    // Whatever actions you want to perform on click
});

$(".send-chat-button:first").trigger("click"); // Executes the click event handler

trigger(event) will execute whatever specified events that are attached to an element at any point in the code.

If you want to use pure JavaScript, there's already a good answer here. As I said though, jQuery makes this extremely simple.

Community
  • 1
  • 1
Henry A.
  • 391
  • 2
  • 19