JavaScript:复制的内容自动添加版权信息 How to automatically append text to text copied with JavaScript

There are two main ways to add extra info to copied web text.

1. Manipulating the selection

The idea is to watch for the copy event, then append a hidden container with our extra info to the dom, and extend the selection to it.
This method is adapted from this article by c.bavota. Check also jitbit‘s version for more complex case.

  • Browser compatibility: All major browsers, IE > 8.
  • Demo: Sources Demo.
  • Javascript code:
        function addLink() {
            //Get the selected text and append the extra info
            var selection = window.getSelection(),
                pagelink = '<br /><br /> Read more at: ' + document.location.href,
                copytext = selection + pagelink,
                newdiv = document.createElement('div');
            //hide the newly created container
   = 'absolute';
   = '-99999px';
            //insert the container, fill it with the extended text, and define the new selection
            newdiv.innerHTML = copytext;
            window.setTimeout(function () {
            }, 100);
        document.addEventListener('copy', addLink);

2. Manipulating the clipboard 操纵剪贴板

The idea is to watch the copy event and directly modify the clipboard data. This is possible using the clipboardData property. Note that this property is available in all major browsers in read-only; the setData method is only available on IE.

  • Browser compatibility: IE > 4.
  • Demo: jsFiddle demo.
  • Javascript code:
        function addLink(event) {
            var pagelink = '\n\n Read more at: ' + document.location.href,
                copytext =  window.getSelection() + pagelink;
            if (window.clipboardData) {
                window.clipboardData.setData('Text', copytext);
        document.addEventListener('copy', addLink);



本文:JavaScript:复制的内容自动添加版权信息 How to automatically append text to text copied with JavaScript


Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.