To add copyright information to a blog today, add copyright information not only at the end of every blog post, but also on the copy function anywhere within the blog

Oncopy, onpaste, and oncut events

The above events are copy, paste, and cut events, which return the ClipboardEvent event object.

Paste event – a single click to create a hexo markdown file that is compatible with the setData() method in Chrome is not compatible after I have repeatedly tested it.

So how do you limit the ability to copy within your blog and add copyright information

After several attempts, you notice one detail: the onCopy, oncut, and onpaste events all start before the actual copy, cut, and paste operations! Before!!!!! Before!! Trigger, important things to say three times.

Development idea: so if you want to add your own copyright information when copying, just need to modify our selected content

Step 1: The browser adds a copy event to retrieve the first selected HTML content

window.addEventListener('copy'.function(event{    
    // Get the selected part of the browser
    const selection = window.getSelection();


    Call cloneContents() to copy the DocumentFragment object and get the selected HTML content
    const range = selection.getRangeAt(0);
    const docFragment = range.cloneContents();
    const hiddenBox = document.createElement('div'); 
    hiddenBox.style.position='absolute'; 
    hiddenBox.style.left='-99999px'; 
    
    hiddenBox.appendChild(docFragment);    
    let copytext = hiddenBox.innerHTML;
Copy the code

Step 2: Add copyright information

     // Add the copyright information suffix
    copytext += '<br>< BR >${location.href}Source: < br > < a href = "https://db324246.github.io/" > cat. の cardboard boxes < / a > < br > copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source. `;
Copy the code

Third part: add a hidden div, add the modified content, and then modify the browser selected content can be

    // Add a hidden div to modify the browser's selection for copying
    var newdiv = document.createElement('div'); 
    newdiv.style.position='absolute'; 
    newdiv.style.left='-99999px'; 


    document.body.appendChild(newdiv); 
    newdiv.innerHTML = copytext; 


    selection.selectAllChildren(newdiv); 


    window.setTimeout(function({ 
      document.body.removeChild(newdiv); 
    },0);
}
Copy the code

This is my blog [Cat eleven Cartons], welcome to learn and communicate