写一个方法,当复制页面中的内容时,同时把版权信息也复制上
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:
addCopyrightOnCopy()
function: This function sets up the event listener.document.addEventListener('copy', ...)
: This listens for the 'copy' event, which is triggered when the user copies something.window.getSelection()
: This gets the text that the user has selected.selection.toString()
: This converts the selection to a string.copyrightNotice
: This variable holds the copyright notice. Customize this with your own information. Using thenew Date().getFullYear()
dynamically updates the year.if (copiedText.length > 0)
: This check ensures the copyright notice isn't added if nothing is selected.e.preventDefault()
: This is crucial. It prevents the default copy behavior, allowing us to modify the copied content.e.clipboardData || window.clipboardData
: This handles cross-browser compatibility for accessing the clipboard data.clipboardData.setData('text/plain', copiedText + copyrightNotice)
: This sets the data that will be copied to the clipboard. It appends thecopyrightNotice
to thecopiedText
.addCopyrightOnCopy();
: This call actually executes the function and sets up the event listener.
How to use it:
-
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.