在javascript中以编程方式填写并提交textarea

问题描述:

我正在尝试使用普通的JS或Jquery自动提交对我的Steemit帖子的回复。

I'm trying to automate the submission of replies to my Steemit posts using plain JS or Jquery.

我使用了下面的javascript代码,但按钮仍然被禁用,因此不允许发布回复/评论。

I used the javascript code below but the button remains disabled and therefore does not allow to post the reply/comment.

如何在textarea上正确触发keydown / keypress / keyup事件以模拟用户经典交互发送回复?

How can I correctly trigger keydown / keypress / keyup events on the textarea in order to simulate the user "classic" interaction to send a reply?

谢谢

目标示例: https://steemit.com/usa/@gaottantacinque/happy-4th-七月

在开发工具控制台中:

function nap (durationMs) {
  new Promise(resolve => setTimeout(() => resolve(), durationMs))
}

async function replyToPost() {
  var replyBtn = document.getElementsByClassName("PostFull__reply")[0]
    .getElementsByTagName('a')[0];
  replyBtn.click();
  await nap(1000);
  var textarea = document.getElementsByTagName('textarea')[0];
  const msg = 'My programmatically generated comment goes here';
  textarea.focus();
  textarea.click();
  textarea.value = msg; // textarea.innerHTML = msg; textarea.innerText = msg;
  await nap(100);
  var postReplyBtn = document.querySelectorAll('[type=submit]')[1];
  // postReplyBtn.disabled = false;
  postReplyBtn.click();
}

replyToPost();

注意:
此代码填充textarea但按钮仍处于禁用状态。只需手动点击textarea并输入任何按钮即可启用该按钮。

Notes: This code fills the textarea but the button is still disabled. Simply manually clicking on the textarea and typing anything the button gets enabled instead.

此外,在背景上单击例如但在没有时,以编程方式插入的textarea值会消失正常输入。

Also, the textarea value inserted programmatically disappears after clicking for instance on the background but it does not when entered normally.

在尝试了所有内容之后,我发现问题似乎是React中触发onchange for textareas的错误。

After trying everything, I found out that the problem seems to be a bug in React on triggering onchange for textareas.

有关错误的更多信息

有一种解决方法..

function setNativeValue(element, value) {
  const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
  const prototype = Object.getPrototypeOf(element);
  const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;

  if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value);
  } else {
    valueSetter.call(element, value);
  }
}

var textarea = document.getElementsByTagName('textarea')[0];
setNativeValue(textarea, 'My automated comment here');
textarea.dispatchEvent(new Event('input', { bubbles: true }));