You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为网站用户复制粘贴的文本添加自定义附加宣传语?

实现复制文本自动添加自定义宣传语的方案

嘿,这个需求其实挺实用的,能帮你的网站在用户分享内容时获得额外曝光。我给你拆解下具体的实现思路和代码,一步步来你就能搞定!

核心原理

本质上就是监听浏览器的copy事件,拦截默认的复制行为,然后把用户选中的文本和你自定义的宣传语拼接起来,再写入剪贴板。整个过程用户感知不到额外操作,体验很顺畅。

基础代码实现

下面是最通用的纯文本版本代码,直接放到你的网站脚本里就能用:

document.addEventListener('copy', function(e) {
  // 获取用户选中的文本,去掉首尾空白
  const selectedText = window.getSelection().toString().trim();
  
  // 要是没选中内容,直接跳过,不干扰正常复制
  if (!selectedText) return;

  // 这里替换成你的自定义宣传语,格式随意调整
  const promoText = `\n\nRead more: 你的网站名称 - 当前内容标题 | 你的网站标识`;
  
  // 拼接选中的文本和宣传语
  const finalText = selectedText + promoText;

  // 阻止浏览器默认的复制行为,不然会覆盖我们的内容
  e.preventDefault();

  // 把新内容写入剪贴板,兼顾新旧浏览器兼容性
  if (e.clipboardData) {
    e.clipboardData.setData('text/plain', finalText);
  } else if (window.clipboardData) {
    // 兼容IE这类老浏览器,现在用得少但可以加上兜底
    window.clipboardData.setData('Text', finalText);
  }
});

优化建议(让效果更贴合需求)

  1. 动态生成宣传语:比如根据当前页面的文章标题来定制,让宣传语更精准。比如你可以获取页面的标题元素:

    const articleTitle = document.querySelector('h1').textContent;
    const promoText = `\n\nRead more: ${articleTitle} | 你的网站名称`;
    
  2. 限制最小选中长度:避免用户复制几个字就被加宣传语,影响体验。比如只在选中超过15个字符时才添加:

    if (selectedText.length < 15) return;
    
  3. 支持富文本格式:如果你的网站内容带样式(比如歌词的排版),想要复制后保留格式同时加宣传语,可以处理text/html格式:

    const selectedHtml = window.getSelection().getRangeAt(0).cloneContents();
    const promoHtml = `<p>\n\nRead more: ${articleTitle} | 你的网站名称</p>`;
    const div = document.createElement('div');
    div.appendChild(selectedHtml);
    div.innerHTML += promoHtml;
    e.clipboardData.setData('text/html', div.innerHTML);
    e.clipboardData.setData('text/plain', finalText); // 同时保留纯文本版本
    

实际场景示例(像MetroLyrics那样)

假设你的页面是歌词站,选中的歌词是:

Hast du etwas Zeit für mich? Dann singe ich ein Lied für dich Von neunundneunzig Luftballons Auf ihrem Weg zum Horizont Denkst du vielleicht grad an mich? Dann singe ich ein Lied für dich Von neunundneunzig Luftballons Und dass sowas von sowas kommt

你可以通过页面元素获取歌曲名和标题,然后生成对应的宣传语:

document.addEventListener('copy', function(e) {
  const selectedText = window.getSelection().toString().trim();
  if (!selectedText || selectedText.length < 20) return;

  // 假设页面上有歌曲名和标题的元素
  const artistName = document.querySelector('.artist-name').textContent;
  const songTitle = document.querySelector('.song-title').textContent;
  const promoText = `\n\nRead more: ${artistName} - ${songTitle} Lyrics | 你的歌词站名称`;
  
  const finalText = selectedText + promoText;
  
  e.preventDefault();
  e.clipboardData.setData('text/plain', finalText);
});

这样用户复制后粘贴出来的内容就和MetroLyrics的效果一模一样啦!

内容的提问来源于stack exchange,提问作者TerranRich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:38:41