最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Modify Clipboard content after copy event: JavaScript, jQuery - Stack Overflow

programmeradmin20浏览0评论

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?

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?

Share Improve this question edited Feb 7, 2017 at 12:31 Geeky Ninja asked Feb 7, 2017 at 12:17 Geeky NinjaGeeky Ninja 6,0528 gold badges42 silver badges54 bronze badges 9
  • 2 it throws error., giving us the actual error may help us help you ;) – Wesley Smith Commented Feb 7, 2017 at 12:21
  • Also, why not update the content where it ends up? For example, why not remove them when the user pastes the content in some input etc... Dealing with the clipboard seems unnecessarily complicated – Wesley Smith Commented Feb 7, 2017 at 12:22
  • 2 "Throws error" ... don't you think the error message might be helpful here? – charlietfl Commented Feb 7, 2017 at 12:22
  • Take a look at : stackoverflow.com/questions/400212/… – Ben Temple-Heald Commented Feb 7, 2017 at 12:23
  • "Unexpected call to method or property access." this is the error I'm getting. Also, I wanted to check am I using the correct function to update the clipboard content or not? – Geeky Ninja Commented Feb 7, 2017 at 12:24
 |  Show 4 more comments

4 Answers 4

Reset to default 26

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();
});

To resolve this issue what I have done on copy event I have bind a function i.e. copyToClipboard which creates a textarea at run time, copy modified clipboard data to this text area and then execute a 'CUT' command (to avoid recursive call on copy event). And finally deleting textarea element in finally block.

Code:

$(document).bind('copy', function () {
            var text = window.getSelection().toString().replace(/[\n\r]+/g, '');
            copyToClipboard(text);
        });

        function copyToClipboard(text) {
                var textarea = document.createElement("textarea");
                textarea.textContent = text;
                textarea.style.position = "fixed";
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    return document.execCommand("cut");
                } catch (ex) {
                    console.warn("Copy to clipboard failed.", ex);
                    return false;
                } finally {
                    document.body.removeChild(textarea);
                }
        }

There are two things I can find out.

  1. clipboardData object will be in callback object e passed not in window.
  2. the correct syntax for setData is like below.

For further reference copy Event MDN

document.addEventListener('copy', function(e) {
  console.log('copied');
  e.clipboardData.setData('text/plain', 'Hello World!');
  e.preventDefault();
});

Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.

         $(ElementId).bind('copy', function(event) {
            var selectedText = window.getSelection().toString(); 
            selectedText = selectedText.replace(/\u200B/g, "");

            clipboardData = event.clipboardData || window.clipboardData || event.originalEvent.clipboardData;
            clipboardData.setData('text/html', selectedText);

            event.preventDefault();
          });
发布评论

评论列表(0)

  1. 暂无评论