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
            newdiv.style.position = 'absolute';
            newdiv.style.left = '-99999px';
    
            //insert the container, fill it with the extended text, and define the new selection
            document.body.appendChild(newdiv);
            newdiv.innerHTML = copytext;
            selection.selectAllChildren(newdiv);
    
            window.setTimeout(function () {
                document.body.removeChild(newdiv);
            }, 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) {
            event.preventDefault();
    
            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);

     

原文:http://stackoverflow.com/a/4777746

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