Modify Clipboard content after copy event: JavaScript, jQuery

Geeky Ninja picture Geeky Ninja · Feb 7, 2017 · Viewed 19.4k times · Source

My requirement: When user copy some content from my web page, with text some HTML tags and carriage retun also gets copied. I need to modify the copied content in clipboard i.e. removing carriage retunn and HTML tags.

What I have tried so far: I have captured the copy even using jQuery and get the content of clipboard. See below code.

$(document).bind('copy', function () {
      //getting clipboard content
      var selectedText = window.getSelection().toString();

      //removing carriage retun from content
      selectedText = selectedText.replace(/<\/?[^>]+(>|$)/g, "");

      //Trying to set data in clipboard
      window.clipboardData.setData(selectedText); //Throws error
}

Now, when I tried to setData in clipboard using window.clipboardData.setData(selectedText); , it throws error.

Questions:

1) Am I using the correct function i.e. setData() to modify the clipbard content or not?

2) Can somebody let me know how can I modify the content of clipboard here?

Answer

Andy H. picture Andy H. · Apr 2, 2019

The currently accepted answer is overly complicated, and causes weird behavior where a user's selection is removed after copy.

Here is a much simpler solution:

document.addEventListener('copy', function(e){
  var text = window.getSelection().toString().replace(/[\n\r]+/g, '');
  e.clipboardData.setData('text/plain', text);
  e.preventDefault();
});