写一个方法,当复制页面中的内容时,同时把版权信息也复制上

function addCopyrightOnCopy() {
  document.addEventListener('copy', function(e) {
    const selection = window.getSelection();
    const copiedText = selection.toString();

    // Customize your copyright notice here
    const copyrightNotice = `\n\n© ${new Date().getFullYear()} Your Company. All rights reserved.`;

    if (copiedText.length > 0) {  // Only add copyright if something is actually copied
      e.preventDefault(); // Prevent default copy behavior

      const clipboardData = e.clipboardData || window.clipboardData; // For cross-browser compatibility
      clipboardData.setData('text/plain', copiedText + copyrightNotice);
    }
  });
}

addCopyrightOnCopy();

Explanation:

  1. addCopyrightOnCopy() function: This function sets up the event listener.
  2. document.addEventListener('copy', ...): This listens for the 'copy' event, which is triggered when the user copies something.
  3. window.getSelection(): This gets the text that the user has selected.
  4. selection.toString(): This converts the selection to a string.
  5. copyrightNotice: This variable holds the copyright notice. Customize this with your own information. Using the new Date().getFullYear() dynamically updates the year.
  6. if (copiedText.length > 0): This check ensures the copyright notice isn't added if nothing is selected.
  7. e.preventDefault(): This is crucial. It prevents the default copy behavior, allowing us to modify the copied content.
  8. e.clipboardData || window.clipboardData: This handles cross-browser compatibility for accessing the clipboard data.
  9. clipboardData.setData('text/plain', copiedText + copyrightNotice): This sets the data that will be copied to the clipboard. It appends the copyrightNotice to the copiedText.
  10. addCopyrightOnCopy();: This call actually executes the function and sets up the event listener.

How to use it:

  1. Include this JavaScript code in your HTML file, preferably within <script> tags just before the closing </body> tag. This ensures the DOM is fully loaded before the script runs.

    <html>
    <head>
      <title>Your Website</title>
    </head>
    <body>
      <!-- Your website content here -->
    
      <script>
        // ... (the JavaScript code from above) ...
      </script>
    </body>
    </html>
    

Key improvements over simpler solutions:

  • Handles empty selections: Prevents adding the copyright notice if nothing is selected.
  • Cross-browser compatibility: Works across different browsers.
  • Dynamic year: The year in the copyright notice updates automatically.

This improved solution provides a more robust and user-friendly way to add copyright information when copying content from your website. Remember to customize the copyrightNotice with your specific information.

posted @ 2024-12-10 06:03  王铁柱6  阅读(21)  评论(0)    收藏  举报