preventDefault does not work in onPaste

In a regular textarea, calling e.preventDefault() from onPaste cancels the paste. See for example jsfiddle where pasting is totally blocked in the textarea.

However it seems in CM this is broken. See for example jsfiddle where pasting in CM works even though e.preventDefault() is called.

Any help with this ? Thanks!

This is not broken, it is simply not a feature that CodeMirror has. You can do something similar with a "beforeChange" event handler, by checking whether the origin field of the even is "paste" and blocking such events.

Let me give an example of when this becomes needed - supposed when the user pastes html that was copied from an outside program (ie gmail) I want to add it to CM as markdown.

So if the user copied XX in bold from a gmail msg then pasted into CM I have to access the onPaste event to get clipboard data:

  • capture onPaste with cm.getWrapperElement().addEventListener(‘paste’, function(e) …
  • get the html text with e.clipboardData.getData(‘text/html’);
  • create a markdown representation: ** XX **
  • insert it to CM with replaceRange

The issue is by this stage the text was already inserted by CM and so it’s there twice, first as text and then followed by the markdown I added in onPaste.

I managed to solve my issue by calling cm.undo() from onPaste. It works but feels quite ugly. Another option is to block paste in beforeChange, again ugly as I’m basically handling paste twice in two different places. Perhaps the clipboardData object can be made available to beforeChange ? or is there a better way to solve this ?


I had a similar problem - in an older version of CodeMirror, it was possible to cancel the paste event, but it appears that the paste functionality has been refactored and this no longer works.

I wouldn’t call undo(), that seems to be a lot of wasted processing if you do that. I would do as marijn suggested - set up a beforeChange listener and cancel the change if it is a paste.

Yes thanks barelyfitz, that’s true but I find handling paste in two different places complicated. For example using the scenario above, if there is no html in the clipboard I want to simply do nothing in onPaste and allow the default CM paste - so cancelling paste in beforeChange becomes tricky

1 Like

I guess all supported browsers now have a “paste” event, so we can fire this as a DOM event. Implemented in this patch.

thank you !