Javascript 如何向复制的web文本添加额外信息

Javascript 如何向复制的web文本添加额外信息,javascript,clipboard,Javascript,Clipboard,一些网站现在使用JavaScript服务,从中向复制的内容添加文本 如果您使用此选项从网站复制文本,然后粘贴,则会在文本底部获得指向原始内容的链接 Tynt也会跟踪这一情况。这是一个巧妙的把戏,做得很好 他们这样做的脚本令人印象深刻——他们并没有试图操纵剪贴板(默认情况下只有旧版本的IE才允许他们这样做,而且应该始终关闭),而是操纵实际的选择 因此,当您选择一块文本时,额外的内容将作为隐藏的添加到您的选择中。粘贴时,将忽略额外样式,并显示额外链接 这实际上是很容易用简单的文本块做的,但是当你考虑

一些网站现在使用JavaScript服务,从中向复制的内容添加文本

如果您使用此选项从网站复制文本,然后粘贴,则会在文本底部获得指向原始内容的链接

Tynt也会跟踪这一情况。这是一个巧妙的把戏,做得很好

他们这样做的脚本令人印象深刻——他们并没有试图操纵剪贴板(默认情况下只有旧版本的IE才允许他们这样做,而且应该始终关闭),而是操纵实际的选择

因此,当您选择一块文本时,额外的内容将作为隐藏的
添加到您的选择中。粘贴时,将忽略额外样式,并显示额外链接

<>这实际上是很容易用简单的文本块做的,但是当你考虑在不同浏览器中的复杂HTML中的所有选择时都会发生噩梦。

我正在开发一个web应用程序-我不希望任何人能够跟踪复制的内容,我希望额外的信息包含上下文内容,而不仅仅是一个链接。在这种情况下,Tynt的服务并不合适

有人知道提供类似功能但不公开内部应用程序数据的开源JavaScript库(可能是jQuery插件或类似库)吗?

2020更新 适用于所有最新浏览器的解决方案

document.addEventListener('copy',(事件)=>{
const pagelink=`\n\n请在以下位置阅读更多信息:${document.location.href}`;
event.clipboardData.setData('text',document.getSelection()+pagelink);
event.preventDefault();
});
Lorem ipsum door sit amet,Concertetur adipsicing elite.

还有一个简短的解决方案:

jQuery( document ).ready( function( $ )
    {
    function addLink()
    {
    var sel = window.getSelection();
    var pagelink = "<br /><br /> Source: <a href='" + document.location.href + "'>" + document.location.href + "</a><br />© text is here";
    var div = $( '<div>', {style: {position: 'absolute', left: '-99999px'}, html: sel + pagelink} );
    $( 'body' ).append( div );
    sel.selectAllChildren( div[0] );
    div.remove();
    }



document.oncopy = addLink;
} );
jQuery(文档).ready(函数($)
{
函数addLink()
{
var sel=window.getSelection();
var pagelink=“

来源:
©文本在此”; var div=$('',{style:{position:'absolute',left:'-9999px'},html:sel+pagelink}); $(“正文”)。追加(div); 选择所有子项(div[0]); div.remove(); } document.oncopy=addLink; } );
我测试并正在使用的jQuery最短版本是:

jQuery(document).on('copy', function(e)
{
  var sel = window.getSelection();
  var copyFooter = 
        "<br /><br /> Source: <a href='" + document.location.href + "'>" + document.location.href + "</a><br />© YourSite";
  var copyHolder = $('<div>', {html: sel+copyFooter, style: {position: 'absolute', left: '-99999px'}});
  $('body').append(copyHolder);
  sel.selectAllChildren( copyHolder[0] );
  window.setTimeout(function() {
      copyHolder.remove();
  },0);
});
jQuery(document).on('copy',函数(e)
{
var sel=window.getSelection();
var copyFooter=
“

来源:
©YourSite”; var copyHolder=$('',{html:sel+copyFooter,样式:{position:'absolute',left:'-9999px'}}); $('body')。追加(版权持有者); 选择所有子项(版权持有者[0]); setTimeout(函数(){ copyHolder.remove(); },0); });
jquery中有一个插件可以实现这一点 从项目自述 此脚本在调用复制事件之前修改选择的内容,导致复制的选择与用户选择的内容不同

这允许您将内容(如版权信息或其他内容)附加/前置到所选内容


根据MIT许可证发布“

改进答案,在修改后恢复选择,以防止复制后随机选择

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');
    var range = selection.getRangeAt(0); // edited according to @Vokiel's comment

    //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);
        selection.removeAllRanges();
        selection.addRange(range);
    }, 100);
}

document.addEventListener('copy', addLink);
函数addLink(){
//获取所选文本并附加额外信息
var selection=window.getSelection(),
pagelink='

阅读更多信息,请访问:'+document.location.href, copytext=选择+页面链接, newdiv=document.createElement('div'); var range=selection.getRangeAt(0);//根据@Vokiel的注释编辑 //隐藏新创建的容器 newdiv.style.position='absolute'; newdiv.style.left='-9999px'; //插入容器,用扩展文本填充,然后定义新选择 文件.body.appendChild(newdiv); newdiv.innerHTML=copytext; 选择。选择所有子项(newdiv); setTimeout(函数(){ 文件.body.removeChild(newdiv); selection.removeAllRanges(); 选择。添加范围(范围); }, 100); } 文件。附录列表(“副本”,附录链接);
2018年的改进

document.addEventListener('copy', function (e) {
    var selection = window.getSelection();
    e.clipboardData.setData('text/plain', $('<div/>').html(selection + "").text() + "\n\n" + 'Source: ' + document.location.href);
    e.clipboardData.setData('text/html', selection + '<br /><br />Source: <a href="' + document.location.href + '">' + document.title + '</a>');
    e.preventDefault();
});
document.addEventListener('copy',函数(e){
var selection=window.getSelection();
e、 clipboardData.setData('text/plain',$('').html(selection++.text()++“\n\n”+'源代码:'+document.location.href);
e、 setData('text/html',selection+'


源:'); e、 预防默认值(); });
这是一个普通的javascript解决方案,来自上面修改过的解决方案,但支持更多浏览器(跨浏览器方法)


这是上面两个答案的汇编+与Microsoft Edge的兼容性。

我还在末尾添加了对原始选择的恢复,这在任何浏览器中都是默认情况

function addCopyrightInfo() {
    //Get the selected text and append the extra info
    var selection, selectedNode, html;
    if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount) {
            selectedNode = selection.getRangeAt(0).startContainer.parentNode;
            var container = document.createElement("div");
            container.appendChild(selection.getRangeAt(0).cloneContents());
            html = container.innerHTML;
        }
    }
    else {
        console.debug("The text [selection] not found.")
        return;
    }

    // Save current selection to resore it back later.
    var range = selection.getRangeAt(0);

    if (!html)
        html = '' + selection;

    html += "<br/><br/><small><span>Source: </span><a target='_blank' title='" + document.title + "' href='" + document.location.href + "'>" + document.title + "</a></small><br/>";
    var 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.
    selectedNode.appendChild(newdiv); // *For the Microsoft Edge browser so that the page wouldn't scroll to the bottom.

    newdiv.innerHTML = html;
    selection.selectAllChildren(newdiv);

    window.setTimeout(function () {
        selectedNode.removeChild(newdiv);
        selection.removeAllRanges();
        selection.addRange(range); // Restore original selection.
    }, 5); // Timeout is reduced to 10 msc for Microsoft Edge's sake so that it does not blink very noticeably.  
}

document.addEventListener('copy', addCopyrightInfo);
函数addCopyrightInfo(){
//获取所选文本并附加额外信息
变量选择,selectedNode,html;
if(window.getSelection){
var selection=window.getSelection();
if(selection.rangeCount){
selectedNode=selection.getRangeAt(0).startContainer.parentNode;
var container=document.createElement(“div”);
container.appendChild(selection.getRangeAt(0.cloneContents());
html=container.innerHTML;
}
}
否则{
调试(“未找到文本[选择]”)
返回;
}
//保存当前所选内容,以便稍后重新恢复。
var range=selection.getRangeAt(0);
如果(!html)
html=''+选择;
html+=“

来源:
”; var newdiv=document.createElement('div'); //隐藏新创建的容器 newdiv.style.position='absolute'; newdiv.style.left='-9999px'; //插入容器,用扩展文本填充,然后定义新选择。 为Microsoft Edge浏览器选择了Node.appendChild(newdiv);//*以便页面不会滚动到底部。 newdiv.innerHTML=html; 选择。选择所有子项(newdiv); wi
function addCopyrightInfo() {
    //Get the selected text and append the extra info
    var selection, selectedNode, html;
    if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount) {
            selectedNode = selection.getRangeAt(0).startContainer.parentNode;
            var container = document.createElement("div");
            container.appendChild(selection.getRangeAt(0).cloneContents());
            html = container.innerHTML;
        }
    }
    else {
        console.debug("The text [selection] not found.")
        return;
    }

    // Save current selection to resore it back later.
    var range = selection.getRangeAt(0);

    if (!html)
        html = '' + selection;

    html += "<br/><br/><small><span>Source: </span><a target='_blank' title='" + document.title + "' href='" + document.location.href + "'>" + document.title + "</a></small><br/>";
    var 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.
    selectedNode.appendChild(newdiv); // *For the Microsoft Edge browser so that the page wouldn't scroll to the bottom.

    newdiv.innerHTML = html;
    selection.selectAllChildren(newdiv);

    window.setTimeout(function () {
        selectedNode.removeChild(newdiv);
        selection.removeAllRanges();
        selection.addRange(range); // Restore original selection.
    }, 5); // Timeout is reduced to 10 msc for Microsoft Edge's sake so that it does not blink very noticeably.  
}

document.addEventListener('copy', addCopyrightInfo);