Reputation: 2550
Adding an oncopy
handler to an input field to get some custom behaviour with no text selected works in Safari on macOS (and other browsers), but on Safari on iPad, nothing happens when pressing ⌘+C.
Is it possible to trigger this on Safari on iPad?
Here's a simple example that doesn't work on Mobile Safari:
<input type="textbox" oncopy="alert('copy!')">
Upvotes: 0
Views: 299
Reputation: 171
According to Safari Supported Attributes , oncopy
is a JavaScript delegate. Therefore, JavaScript solution for this should work on any Safari running device. JavaScript detects keyboard shortcuts in this solution.
Sources: How TO - Copy Text to Clipboard , How to detect copy paste commands , Toptal keycodes library & Safari HTML Reference
// Global variable to get input value (Input element must have an id)
let justCopiedFrom = '';
// Clicked element's value into dynamic variable
function inputToVar(x) {
justCopiedFrom = x.id;
}
// Detect [⌘/Ctrl + C] & [⌘/Ctrl + V]
document.body.addEventListener("keydown",function(e){
e = e || window.event;
var key = e.which || e.keyCode; // keyCode detection
var ctrl = e.ctrlKey ? e.ctrlKey : ((key === 17) ? true : false); // ctrl detection
var cmd_h = e.metaKey ? e.metaKey : ((key === 91) ? true : false); // ⌘ detection
if ( key == 86 && ctrl || key == 86 && cmd_h ) {
// Copy the text inside the text field
console.log("⌘/Ctrl + V");
} else if ( key == 67 && ctrl || key == 67 && cmd_h ) {
let valueOf = document.getElementById(justCopiedFrom);
// Select the text field
valueOf.select();
valueOf.setSelectionRange(0, 99999); // For mobile devices
navigator.clipboard.writeText(valueOf.value);
console.log(`⌘/Ctrl + C (${valueOf.value})`);
}
},false);
<!-- Input must have an Id so it can be passed with JS function (inputToVar) -->
<p><small>Add some random text here and try copy and paste keyboard shortcuts</small></p>
<input id="text-input" type="textbox" onclick="inputToVar(this);">
Upvotes: 2