javascript - 如何向复制的网页文本添加额外信息

标签 javascript clipboard

一些网站现在使用来自 Tynt 的 JavaScript 服务将文本附加到复制的内容。

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

Tynt 还会在发生这种情况时对其进行跟踪。这是一个巧妙的技巧,做得很好。

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

因此,当您选择一段文本时,额外的内容将作为隐藏的 <div> 添加。包含在您的选择中。当您粘贴时,额外的样式将被忽略并显示额外的链接。

这对于简单的文本 block 实际上很容易做到,但是当您考虑在不同浏览器中跨复杂 HTML 的所有可能选择时,这将是一场噩梦。

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

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

最佳答案

2022 年更新

处理富文本格式的更复杂的解决方案。如果您只处理纯文本,2020 年的解决方案仍然适用。

const copyListener = (event) => {
  const range = window.getSelection().getRangeAt(0),
    rangeContents = range.cloneContents(),
    pageLink = `Read more at: ${document.location.href}`,
    helper = document.createElement("div");

  helper.appendChild(rangeContents);

  event.clipboardData.setData("text/plain", `${helper.innerText}\n${pageLink}`);
  event.clipboardData.setData("text/html", `${helper.innerHTML}<br>${pageLink}`);
  event.preventDefault();
};
document.addEventListener("copy", copyListener);
#richText {
  width: 415px;
  height: 70px;
  border: 1px solid #777;
  overflow: scroll;
}

#richText:empty:before {
  content: "Paste your copied text here";
  color: #888;
}
<h4>Rich text:</h4>
<p>Lorem <u>ipsum</u> dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.</p>
<h4>Plain text editor:</h4>
<textarea name="textarea" rows="5" cols="50" placeholder="Paste your copied text here"></textarea>
<h4>Rich text editor:</h4>
<div id="richText" contenteditable="true"></div>


2020 更新

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

请注意,即使粘贴到富文本编辑器中,此解决方案也会去除富文本格式(例如粗体和斜体)。

document.addEventListener('copy', (event) => {
  const pagelink = `\n\nRead more at: ${document.location.href}`;
  event.clipboardData.setData('text/plain', document.getSelection() + pagelink);
  event.preventDefault();
});
Lorem ipsum dolor sit <b>amet</b>, consectetur <i>adipiscing</i> elit.<br/>
<textarea name="textarea" rows="7" cols="50" placeholder="paste your copied text here"></textarea>


[较旧的帖子 - 2020 年更新之前]

有两种主要方法可以向复制的网络文本添加额外信息。

  1. 操纵选择

我们的想法是监视复制事件,然后将一个包含我们额外信息的隐藏容器附加到dom,并将选择扩展到它。
此方法改编自 this article通过 c.bavota。也检查 jitbit's version对于更复杂的情况。

  • 浏览器兼容性:所有主流浏览器,IE > 8。
  • 演示:jsFiddle demo .
  • Javascript 代码:

    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);
  1. 操作剪贴板

思路是监听copy事件,直接修改剪贴板数据。这可以使用 clipboardData 属性。请注意,此属性在所有主流浏览器中均可用,且只读setData 方法仅在 IE 上可用。

  • 浏览器兼容性:IE > 4.
  • 演示:jsFiddle demo .
  • Javascript 代码:

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

关于javascript - 如何向复制的网页文本添加额外信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29178886/

相关文章:

php - 垂直对齐 div 但保持水平位置不变

javascript - Openlayers - 转换时 LonLat 不正确?

python - 将图像复制到剪贴板并保留透明度

selenium - 使用 Protractor 和Webdriver在自动测试中启用剪贴板

c# - 以编程方式 (C#) 将 Excel 转换为图像

javascript - 在 Jest 测试中,shallow 抛出意外的 token < 错误

javascript - 你如何在 switch 语句中使用 NaN case?

javascript - 如何水平对齐 flex 盒中的一项?

java - 更改剪贴板内容时调用方法

java - 清除 RCP 中的系统剪贴板