Trouble automatically typing text into textarea - javascript

This is a rather long question, as I've tried to include as much detail as I could. If you'd like to skip to the actual question, please see the very last paragraph.
I'm attempting to write a bot to take commands to roll a die like /r 1d20+2, evaluating, and sending the response in Javascript within a chat box on the website streamyard.com (as that's what my DM is using to stream D&D).
What I'm having trouble with is "typing" into the textarea field. Here's the HTML of the chat box on the page:
<div class="Chat__Wrap-eYhJOs AJLtK">
<ul class="Chat__Comments-dUewnW eqLtEG">
<li class="Comment_Wrap-lbwIWt klCgOs">
<div class="Comment_TextWrap-hSuVQ gHYXCH">
<p class="Text__StyledText-guhEiE bLDoWl" color="default">test</p>
</div>
</li>
</ul>
<form class="ChatInput__Form-eqBCnG iHgCda">
<div class="ChatInput__InputWithSmallGutter-fOaQzB dEaxxd Input__Wrap-kXBxwI iUPDqt">
<label>
<textarea class="sc-bdVaJa eFZRmf"></textarea>
</label>
</div>
<button class="Button_Wrap-ivpgWU dSirvr ButtonBase__WrapperButton-bsASeg cylsQk" type="submit" color="primary">
<span class="Button__InnerSpan-iZsIhM jVWFud">Send</span>
</button>
</form>
</div>
I'm able to get a handle to the text area with the following:
var textbox = document.getElementsByClassName("sc-bdVaJa eFZRmf")[1];
And I can insert text into it with the following:
textbox.value = 'test';
textbox.innerText = 'test';
Which causes the textarea to show the value (in this case "test") as being typed in (specifically the textbox.value command does this). However, when I go to "send" the message by using the following:
var button = document.getElementsByClassName("Button__Wrap-ivpgWU dSirvr ButtonBase__WrapperButton-bsASeg cylsQk");
button[1].click();
It doesn't send the chat message that I've "typed" in. It sends nothing at all and doesn't even clear out the textarea as if the button were clicked. Furthermore, if I manually click the button, the same thing happens. Now, if I manually click in the textarea and type anything into it, such as adding a space after the text I programmatically inserted into it, then execute the code above to click the button, it will send the message.
So, this makes me think that there's something it's detecting when the keyboard presses a button that I'm not accounting for by just setting the textarea value. After some Googling, I've found about triggering the onchange event. So, I've tried the following:
if ("createEvent" in document) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
textbox.dispatchEvent(evt);
}
else {
textbox.fireEvent("onchange");
}
However, this simply results in the same as before. I've also tried simulating a key press in the textarea with code like the following:
textbox.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}));
However, that also does not seem to work as the "Send" button does not seem to work (and the textarea doesn't seem to populate with the specified key of "a"). But once again, if I were to manually type something into the box, the "Send" button now works as it detected something being entered. I also tried dynamically importing jQuery in and using jQuery to simulate a keypress as seen below:
var e1 = jQuery.Event("keydown");
e1.which = 97;
$('textarea.sc-bdVaJa').last().trigger(e1);
var e2 = jQuery.Event("keyup");
e2.which = 97;
$('textarea.sc-bdVaJa').last().trigger(e2);
But that simply resulted in the same as above, the 'a' (decimal 97) didn't appear in the textarea, nor did the "Send" button work.
What I thought would be one of the simplest parts of this little project, sending a string of text to a textarea, is turning out to be a lot more difficult than I thought. What I'm looking for is, how do I go about getting a web page to register that new text has been entered into a textarea so that I may "click" a button and have it send the text to a chat?

While this doesn't directly solve the issue, this is what I did to get this working. Instead of using the textarea and Send button on the webpage, I decided to cut out the middleman and view the network traffic that's send when a post is made. I then use JavaScript to send a similar request to the server and it successfully posts the message. Here's how I did that.
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/api/broadcasts/dug95avkgq/chat", true);
xhttp.setRequestHeader("content-type", "application/json");
xhttp.send('{"text":"<MESSAGE>","name":"<USERNAME>","clientId":"<ID>","color":"#22653f","csrfToken":"<TOKEN>"}');

Related

Give an input button with no value HTML tag a different value

I'm using UserWP plugin in Wordpress and on my registration page I have the form and the button which says "Submit Query" - not the best text. I'd much rather have "Register".
There's no option in the settings to change the button text so trying to utilise another method.
The HTML string for the button is:
<input type="submit" name="uwp_register_submit" class="form-control btn btn-primary btn-block text-uppercase uwp_register_submit">
So there is no "value" for the text.
My aim is to "inject" the value="Register" into the HTML string. I believe this can be done with a JavaScript snippet, but not being the best at JS, I'm struggling to achieve it.
Lots of googling found some JS code that finds a text string in the identifier and replaces it, however I cannot seem to get this working.
const button = document.querySelector('input');
button.addEventListener('click', updateButton);
function updateButton() {
if (button.value === '') {
button.value = 'Register';
}
}
I realise this would only take effect on click, so when the button is pressed. So tried something like:
const button = document.querySelector('input');
if (button.value === '') {
button.value = 'Register';
}
Again, no success.
And I also saw something about using jquery? So tried the following without success.
$('.btn').val('Register');
I simply want to target the class of the button and tell it to give a value of "Register" - I bet it's an easy solution for someone, but not me...
In general you can achieve that by getting the element and setting the value as you try.
But the line document.querySelector('input'); gives you back the first matching element back. See MDN Document.querySelector
So if there are more than one input fields, it will take the first input, which may not be your submit input.
An alternative would be to search for the specific name of the input field.
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector("[name='uwp_register_submit']").value = "Register";
});
If that field exists multiple times, use querySelectorAll and combine it with an loop.
In your specific case it would maybe the better way to change the default translation for english. Have a look at the documentation. It looks more complicated as it is.

Get value without onclick

I want to make a WhatsApp share button for my Android app. All is set, the only problem is that I can get the textarea value only when I click on a button:
<button onclick="GetValue ();">Get the value of the textarea!</button>
I want to GetValue(); without the onclick.
This is my WhatsApp code:
Share
I want the textarea value in the data-text attribute and I am using it like above but it doesn’t work.
This is my textarea:
<textarea id="input_output" style="width:95%;" rows="10" wrap="soft">Enter Text Here..
</textarea>
Is there any way to get the value without clicking the button?
This is my function:
GetValue () {
var area = document.getElementById ("input_output");
alert (area.value);
}
Using javascript
document.getElementById("input_output").value
Using jQuery
$('#input_output').val();
EDIT:
Probably misunderstood, but it's very hard to understand your question.
As a javascript click event always fires before the "href" sets in, you can set the value when the link is clicked.
$('a').click(function(){
$(this).attr('data-text', $('#input_output').val());
return true;
});

Filling in specific fields in a form on a website [Greasemonkey / Javascript]

I'm fairly new to scripting, but I was looking for a way to automatically fill in certain fields on a certain webpage on a click of a button.
So far I have managed this:
//Adding a button
x=0
var input=document.createElement("input");
input.type="button";
input.value=x;
input.onclick= fillValuesInTextBoxes;
input.setAttribute("style", "font-size:18px;position:absolute;top:120px;right:40px;");
document.body.appendChild(input);
function fillValuesInTextBoxes()
{
document.getElementById('username').value="MyUserName"
document.getElementById('password').value="MyPassWord"
}
It seems I'm off with the Ids or anything else, but I can't figure out what exactly. The website I've taken for references is Darkthone login page (See include).
Maybe somebody could tell me how to find the propper Id or Tag of each field?
And how to add certain input to those fields in a simple way?
"(See include)" - there is no #include shown in the snippet, also no #run-at. If you don't get any button at all, it might be that <body> isn't initialized yet.
For error checking put your code inside a
try{
// here the code...
}
catch(e)
{
console.log(e);
}
Then open the console in your browser. (Ctrl+Shift+k in Firefox, Chrome is similar)
In the console you can also inspect elements. Rightclick on an element and select "inspect" in the context menu. You will find, that the "Username or Email" <input> has the id "user_login" for example.
document.getElementById('email_address').value = email;
document.querySelector('input[type=password]').value = password;

Creating Ask Function in Javascript

I'm pretty new to Javascript, so I figured I'd start on a Text Based Game to start out. What I need to do, is to be able to detect when the game is waiting for a command, and when the game is waiting for an answer. Here's what I've got.
var textIn = document.getElementById('input-textbox');
var textOut = document.getElementById("output-textbox");
function process(input) {
var command = input.split(" ")[0];
if(command == "help") {
return "Help dialog";
}else{
return "Unknown command: " + input + ". Please type /help for a list of commands.";
}
}
function go() {
var input = textIn.value;
textIn.value = "";
output(process(input));
}
function output(text){
textOut.value += text + "\n";
}
function createPlayer(){
output("Please Type Your Name")
// Wait for player response and set it as a variable.
}
createPlayer();
What would be the best way to implement this?
You have a few options, you could use onclick and have a button that the user clicks and then call your functionality to fill in the answer for your HTML answer (id="output-textbox" in your example)<-- My vote *.
... or you could choose to check on which element is focused or if tab/enter is hit while in the input box and then put your answer field after the tab/enter is hit. I think the latter method, you should have a HTML5 placeholder attribute to say "hit tab{enter} when finished" or something along those lines and then check for the tab while focused on the element -- this could be accomplished with jQuery selectors or override the current focus method for that input element or potentially use document.activeElement to see what is focused on and then if it is the answer that is focused on and the input isn't blank fill it in, etc, etc, etc.
*If you are new to Javascript, I say have two buttons (one labeled 'answer' and one labeled 'clear'), and then use the onclick attribute for HTML button elements to call a Javascript method easily. This will get you started and be more straightforward, double check what you have works for DOM manipulation and move forward to having less buttons and more sleek DOM manipulation.
Good luck!
A very simple implementation is to use a form with a submit listener that cancels submission if all goes to plan. A user can enter text into the input and see the result in the textarea.
The textarea is disabled so users can't enter text into it but script can. Users can enter input then just press enter, or tab to the submit button and press enter, or click the submit button. The script runs on submit, and cancels it so they stay on the same page.
If scripting is disabled, the form will submit and you can handle things at the server.
<form onsubmit="go(); return false;">
<input id="input-textbox">
<textarea id="output-textbox" rows="20" cols="50" disabled></textarea>
<input type="submit" value="Ask question">
</form>

Rails javascript; alert to fire when leaving a field

My ultimate goal is to add some validation to a set of date fields. However, my javascript sucks, so I'm starting small.
I am starting out by trying to get an alert message when a user leaves a field.
(For simplicity I'm just doing it all in my view...) Heres what I go to work...
# html.erb-template
<div class="from_date">
From Date
<input type="text" id="from_date" name="from_date"></input>
</div>
<script>
$("#from_date").blur( function() {
alert("boom!");
});
</script>
Your code seems to be fine - problem is that class and id are named the same, but you want to watch the input field not the surrounding div.
I just made a fiddle from your script and changed
the listener to be attached to the input field's id - and it's working.
the alert into a console.log
see
$("#from_date").blur(function() {.....
// instead of
$(".from_date").blur(function() {.....

Categories