The value is not changed. in tampermonkey, javascript [duplicate]

Solution 1:

There is a built-in DOM method document.execCommand.
In case of an extension, use this code in the content script.

// some.selector may be `input` or `[contenteditable]` for richly formatted inputs
const el = document.querySelector('some.selector');
el.focus();
document.execCommand('insertText', false, 'new text');
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed

It imitates physical user input into the currently focused DOM element so all the necessary events will be fired (like beforeinput, input) with isTrusted field set to true. On some pages the change event should be additionally dispatched as shown above.

You may want to select the current text to replace it entirely instead of appending:

replaceValue('some.selector', 'new text');

function replaceValue(selector, value) {
  const el = document.querySelector(selector);
  if (el) {
    el.focus();
    el.select();
    if (!document.execCommand('insertText', false, value)) {
      // Fallback for Firefox: just replace the value
      el.value = 'new text';
    }
    el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
  }
  return el;
}

Note that despite execCommand being marked as obsolete in 2020, it'll work in the foreseeable future because a new editing API specification is not finished yet, and knowing how slow such things usually move it may take another 5-20 years.

Solution 2:

@wOxxOm, thank you very much ! I used your code solved my problem which has bothered me for long time. I googled many code and article for nearly one month. It works on Facebook and many strong website.

Because execCommand has depredated, I try below code it works well, include Facebook.

function imitateKeyInput(el, keyChar) {
  if (el) {
    const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:'', code:'', location:0};
    el.dispatchEvent(new KeyboardEvent("keydown", keyboardEventInit));
    el.value = keyChar;
    el.dispatchEvent(new KeyboardEvent("keyup", keyboardEventInit));
    el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
  } else {
    console.log("el is null");    
  }
}

The following code can only work on ordinary websites, but it is invalid for strong website.

function fireKeyEvent(el, evtType, keyChar) {
  el.addEventListener(evtType, function(e) {el.value += e.key;}, false);
  el.focus();
  const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:keyChar, code:'', location:0};
  var evtObj = new KeyboardEvent(evtType, keyboardEventInit);
  el.dispatchEvent(evtObj);
}