复制文本时追加自定义内容


DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>

<body>
    <p>copy the codep>

    <p id="result">p>
body>
<script>


    document.addEventListener('copy', function (event) {
        // clipboardData 对象是为通过编辑菜单、快捷菜单和快捷键执行的编辑操作所保留的,也就是你复制或者剪切内容
        let clipboardData = event.clipboardData || window.clipboardData;
        if (!clipboardData) { return; }
        let text = window.getSelection().toString();
        let add = "\n\n******** 内容拼接 ********";
        if (text) {
            // 如果文本存在,首先取消文本的默认事件
            event.preventDefault();

            clipboardData.setData('text/plain', text + add);

            document.querySelector('#result').innerText = text + add;
        }
    });
script>

html>
js