Simulate enter key in text area for automation with javascript, no jQuery

Viewed 886

I'm building an automation tool and I'm trying to automate some comments. The issue I'm facing is that I can't "submit" the comment.

I can get the comment/text in the textarea, I've tried doing .submit() but it just reloads the page, doesn't actually submit the comment. I think the actual submit is triggered by the enter keypress.

I attempted doing .focus() and then simulating the enter key but it didn't work. Another issue might be that I'm running this code inside the browsers console, and i can't focus inside the textarea. I could be wrong though.

Also, the textarea doesn't have an ID, only a class. I'm trying to do this with pure JS, no jQuery.

function enter1() {
    var commentEl = document.querySelector("._2hc0g");

   var keyboardEvent = document.createEvent('KeyboardEvent');
   delete keyboardEvent.which;
   var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent';
   keyboardEvent[initMethod](
     'keydown', // event type : keydown, keyup, keypress
     true, // bubbles
     true, // cancelable
     window, // viewArg: should be window
     false, // ctrlKeyArg
     false, // altKeyArg
     false, // shiftKeyArg
     false, // metaKeyArg
     13, // keyCodeArg : unsigned long the virtual key code, else 0
     13 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
   );
   console.log("beefore querySelector");
   commentEl.focus();
   document.querySelector("._2hc0g").dispatchEvent(keyboardEvent);
   if(document.querySelector("._2hc0g").dispatchEvent(keyboardEvent)){
    console.log("key event worked");
   }
   console.log("after querySelector");
 }

function doComment() {
    var textAreaElement = $("textarea._2hc0g");
    var commentEl = document.querySelector("._2hc0g");

    
    textAreaElement.value = "Great photo here! I love it :)";
    commentEl.focus();
    enter1();
}
doComment();

0 Answers
Related