Copy & CTRL+C event propagation test

by Marek Suscak

HTML

<p>Try to hit CTRL+C (or CMD+C on Mac) without selecting any text on this page.</p>
<p>You can also hit Copy button instead which should trigger the same action but this works just in Internet Explorer (will ask for permission). In Chrome it could work with custom application which has <a href="https://developer.chrome.com/extensions/permissions"> a 'clipboardWrite' permission in its manifest</a>. Don't know how to solve it in Firefox, Opera or Safari yet.</p>
<button>Copy</button>
<textarea>This is a hidden text copied at </textarea>

CSS

textarea {
    position: absolute;
    left: -10000px;
    top: -10000px;
}

p {
    -webkit-user-select: none;  /* Chrome all / Safari all */
    -moz-user-select: none;     /* Firefox all */
    -ms-user-select: none;      /* IE 10+ */
    
    /* No support for these yet, use at own risk */
    -o-user-select: none;
    user-select: none;        
}

JavaScript

$(document).ready(function() {
    // helper function to select value of hidden textarea
    var phantomSelect = function() {
        // NOTE: we could manipulate the value before selecting here as well
        $('textarea').select();
    };
    
    // Keydown event should be the first in the event chain 
    // so we can always select textarea value before copying
    $(document).on('keydown', function(ev) {
        if((ev.ctrlKey || ev.metaKey) && ev.keyCode == 67) {
            phantomSelect(); 
            // NOTE: we can execute ev.preventDefault() which will stop copy event from executing too
        }
    });
    
    // Copy event should fire after the keydown event is fully processed, of course if it didn't call ev.preventDefault
    $(document).on('copy', function(ev) {
/*             alert('0'); */

        if(window.clipboardData) {
/*             alert('1'); */
            window.clipboardData.setData('Text', $('textarea').val() + new Date);        
        } else if(ev.originalEvent.clipboardData) {
/*             alert('2'); */
        
            ev.originalEvent.clipboardData.setData('text/plain', $('textarea').val() + new Date);      
        } else {
            alert('Clipboard Data are not supported in this browser. Sorry.');
        }
        
        ev.preventDefault();
    });

    // Custom copy button to demonstrate the possibility in IE
    $('button').on('click', function(ev) {
        try {
            phantomSelect();
            if(!document.execCommand('copy')) {
                throw "Not supported";
            } else { /* alert('3') */ }
        } catch(ex) {
            alert('This is not supported in current browser');
        }
    });
});