html 右键复制功能实现

处理默认右键复制,添加额外内容

<div id="wrap">这是复制的复制内容div>
    <script>
      var wrap = document.getElementById('wrap')
      wrap.oncopy = function (event) {
        // 通过copy事件监听,阻止将选中内容复制到系统剪切板上
        event.preventDefault()
        // 获取选中内容对象
        const selection = document.getSelection()
        // selection对象重构了toSring()方法,获取selection对象的选中内容
        var selectContent = selection.toString()
        var dealContent =
          selectContent +
          '转载请联系作者,内容地址:xxxxx'
        // 把重写后的内容写入到剪贴板
        event.clipboardData.setData('text/plain', dealContent)
      }
    script>

方法二

    <div id="copy-text">要复制的内容div>
    <button onclick="copyText()">复制按钮button>
    <script>
    const isClipboardApiSupported = () => (navigator && 'clipboard' in navigator)

    console.log(isClipboardApiSupported(),navigator)

    function copyText() {
        const dom = document.getElementById('copy-text');
        copy(dom.innerText);
    }

    async function copy (value) {
        if(isClipboardApiSupported()) {
            await navigator.clipboard.writeText(value)
            alert('复制成功')
        }
     }
    script>

你可能感兴趣的:(html,前端,javascript)