Advanced Method to Disable Copy and Paste Using JavaScript
In web development, preventing end-users from pasting content into textareas can be necessary for data integrity or user experience. To achieve this, custom JavaScript code can provide a solution.
Implementation:
Example Code:
<code class="javascript">$(document).ready(function() { var ctrlDown = false, ctrlKey = 17, cmdKey = 91, vKey = 86, cKey = 67; $(document).keydown(function(e) { if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true; }).keyup(function(e) { if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false; }); $(".no-copy-paste").keydown(function(e) { if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false; }); // Document Ctrl + C/V $(document).keydown(function(e) { if (ctrlDown && (e.keyCode == cKey)) console.log("Document catch Ctrl+C"); if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V"); }); });</code>
Usage:
To use this code, apply the "no-copy-paste" CSS class to textareas where you want to disable copy and paste. In textareas without this class, copying and pasting will function normally.
Note: This solution may not be suitable for all applications, as it does prevent the user from using standard keyboard shortcuts such as Ctrl or Cmd F for find/search. It's important to weigh the trade-offs between usability and security before implementing this measure.
The above is the detailed content of How to Disable Copying and Pasting in Textareas with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!