How to replace selected text with new text in any textbox?

Say for example the user selected this:
enter image description here

How can a chrome extension replace the selected text with something else? The tricky thing is that this is a universal script, not targeted towards a specific website. And dealing with iframes in google docs, for example, can make things even trickier. I’ve tried existing solutions, but they don’t work or are not complete.

In addition, I’ve tried:

function replaceSelectedText(correctedText, activeElementTagName, selectionStart, selectionEnd) {
  const activeElement = document.activeElement;

  if (activeElement.tagName === activeElementTagName) {
    if (activeElement.tagName === 'TEXTAREA' || activeElement.tagName === 'INPUT' && activeElement.type === 'text') {
      const value = activeElement.value;
      activeElement.value = value.slice(0, selectionStart) + correctedText + value.slice(selectionEnd);
    }
  }
}

and

function replaceSelectedText(correctedText, activeElementTagName, selectionStart, selectionEnd) {
  const activeElement = document.activeElement;
  console.log(activeElement);

  if (activeElement.tagName === activeElementTagName) {
    if (activeElement.tagName === 'TEXTAREA' || (activeElement.tagName === 'INPUT' && activeElement.type === 'text')) {
      const value = activeElement.value;
      activeElement.value = value.slice(0, selectionStart) + correctedText + value.slice(selectionEnd);
      activeElement.setSelectionRange(selectionStart, selectionStart + correctedText.length);
      activeElement.focus();
    } else {
      const selection = window.getSelection();
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        range.deleteContents();
        range.insertNode(document.createTextNode(correctedText));
        selection.removeAllRanges();
        range.setStart(range.startContainer, range.startOffset + correctedText.length);
        selection.addRange(range);
      }
    }
  }
}

But perhaps I’m doing things wrong.