Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undo an overridden paste in JS

I have overridden the paste event. I noticed that because the event's default behavior is prevented, it is not currently possible to undo the "paste" with Ctrl+Z.

$(this).on('paste', function (evt) {
  // Get the pasted data via the Clipboard API.
  // evt.originalEvent must be used because this is jQuery, not pure JS.
  // https://stackoverflow.com/a/29831598
  var clipboardData = evt.originalEvent.clipboardData || window.clipboardData;
  var pastedData = clipboardData.getData('text/plain');

  // Trim the data and set the value.
  $(this).val($.trim(pastedData));

  // Prevent the data from actually being pasted.
  evt.preventDefault();
});

Is there a way to override the undo functionality or do the above differently such that Ctrl+Z will work?

Related questions

  • JavaScript get clipboard data on paste event (Cross browser)
  • Paste event modify content and return it at the same place
like image 952
mbomb007 Avatar asked Apr 25 '19 14:04

mbomb007


People also ask

How do you undo text in JavaScript?

You can perform undo and redo by 'CTRL+Z' and 'CTRL+Y' keyboard shortcuts. Document Editor exposes API to do it programmatically.

How to get copied data from clipboard in JavaScript?

Copy and Paste Text // copy text TO the clipboard await navigator. clipboard. writeText('This text is now in the clipboard'); // get text FROM the clipboard let text = await navigator. clipboard.


1 Answers

Use

document.execCommand("insertText", false, $.trim(pastedData));

instead of

 $(this).val($.trim(pastedData));

It will preserve the undo history.

$('#inputElement').on('paste', function (evt) {
  var clipboardData = evt.originalEvent.clipboardData || window.clipboardData;
  var pastedData = clipboardData.getData('text/plain');
  this.select(); // To replace the entire text
  document.execCommand("insertText", false, $.trim(pastedData));
  evt.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="inputElement"></textarea>
like image 62
Munim Munna Avatar answered Sep 29 '22 02:09

Munim Munna