I'm working on a school assignment where I'm attempting to increase the visibility of Ctrl + c
and Ctrl + p
. My goal, right now, is to show what text has been copied in a second textarea
. The code I have 'works' but it's not ideal.
Here is my code (which I have gotten from here and here):
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Ctrl+c Ctrl+v allowed</h3>
<textarea></textarea>
<br>
<br>
<h3>Clipboard</h3>
<textarea id="clipBoard"></textarea>
<script>
$(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;
});
// Document Ctrl + C/V
$(document).keydown(function(e) {
var clip = document.getElementById("clipBoard");
if (ctrlDown && (e.keyCode == cKey))
{
navigator.clipboard.readText()
.then(text => {
clip.value = text;
})
.catch(err => {
});
console.log("Document catch Ctrl+C");
}
if (ctrlDown && (e.keyCode == vKey))
{
console.log("Document catch Ctrl+V");
}
});
});
</script>
There are 2 problems with this solution.
First, the webpage asks for permission to copy. I understand the need for this, but is there a way to get around this?
Second, if a user says no then I can't display the clipbaord text when there is something in the clipboard which would just ruin the assignment.
Is there a way to get around these problems?
Thanks!