Modify clipboard in paste event and paste new text

11 views Asked by At

Is it possible to modify the clipboard in a paste event and to paste that modifed text?

I'm building an app that we first modify the clipboard in a json string, then in the paste event we parse it to json but we don't want it to be pasted a json, we want to paste the attribute text. For example:

{
  "initialCharacters":"5",
  "text": "hello",
}

This is the logic in the paste event:

$(document.body).on('paste', (e) => {
   
      const pastedText = e.originalEvent.clipboardData.getData('text/plain');

      const validSourcesIndex = {
        'gg': 0,
        'gg1': 1,
        'gg3': 2,
        'gg4': 3,
      };

      let parseClipboardData;
      let sourceIndex;

      try {
        parseClipboardData = JSON.parse(pastedText);
        sourceIndex = validSourcesIndex[parseClipboardData.gizmo];
        const restoreClipboard = async () => {
          await navigator.clipboard.writeText(parseClipboardData.text);
        };
        restoreClipboard();
      } catch (error) {
        sourceIndex = 4;
      
    });

This doesn't work, the text pastes as json.

0

There are 0 answers