For an internal tool at my job, I'm trying to intercept and override the ctrl/cmd+c shortcut.
Context: the script below is added to an html file exported from my application. Its purpose is to make sure that, when the user copies a piece of text, my custom markup is written to the clipboard exactly as is, without any of the style elements added by Chrome when you copy text normally.
Functionally, I want it to work exactly like ctrl/cmd+c would normally work, so as not to break any of my colleagues' muscle memory workflows. Some of us use Macs, some PCs, but we all use Chrome.
<script>
document.addEventListener('keydown', function (event) {
event.stopPropagation();
var selected ='';
var element = '';
if ((event.ctrlKey || event.metaKey) && (event.key === 'c' || event.key === 'C')) {
selected = window.getSelection();
if (selected != '') {
var selectedElement = document.createElement('div');
selectedElement.setAttribute('id','selection');
for (var i = 0, len = selected.rangeCount; i < len; ++i) {
selectedElement.appendChild(selected.getRangeAt(i).cloneContents());
}
document.getElementById('export').appendChild(selectedElement);
element = document.getElementById('selection');
} else { element = document.getElementById('export'); }
navigator.clipboard.write([new ClipboardItem({
'text/plain': new Blob([element.innerText], {type: 'text/plain'}),
'text/html': new Blob([element.innerHTML], {type: 'text/html'})
})])
document.getElementById('selection').remove();
}
});
</script>
A keydown event listener is checking for ctrl/cmd combined with "c"/"C". When triggered, the script first checks if a selection exists. If so, the selected text is appended to the document to make Chrome render it, then written to the clipboard, then removed again. This may seem like a roundabout way of doing things, but it's the only way I could find to get to the selection's innerText and innerHTML, and it works.
If nothing is selected, a div element called "export" containing the entire document is written to the clipboard (I figured it would be handy to be able to skip ctrl/cmd+a if you want to copy the entire text).
Anyway, all of that isn't important. My problem is that the script works reliably on Chrome for PC, every time. But when I try it on a Mac, the shortcut seems to slip through about two thirds of the time, i.e., it isn't intercepted and the clipboard contents is what you would get without the script. Really strange: I can hit cmd+c and paste into Clipboard Inspector ten times in a row and the results are unpredictable.
Why would something like this work only some of the time? What am I doing wrong? Is event.metaKey known to be unreliable? Disclaimer: I'm not an experienced coder, be gentle. 🥲