4

What I am doing is programmatically select all text from a webpage and then copy it. The select all works with execCommand but copy doesn't.

Here is my code:

$.ajax({
    url: $('#url').val(),
    type: 'GET',
    success: function(res) {
        $('#result').html(res.responseText);
        $('#result').fadeIn('fast');


        $('#result').focus();
        $('#result').select();

        document.execCommand('selectall');

        // copy does not work ?
        document.execCommand('copy');

    }
});

Here is Example on JsBin

I also tried using flash solution such as ZeroClipboard, however it seems that one has to press their flash object/button explicitly to copy text whereas I wanted to do zeroclip.setText('whatever'); without user's pressing the button.

Can anyone tell how to copy text programmatically?

Dev01
  • 4,082
  • 5
  • 29
  • 45
  • Perhaps, you could do something which I mentioned here: [SOLVED: document execCommand copy not working with AJAX](http://stackoverflow.com/questions/43380921/not-able-to-copy-a-link-directly-when-i-am-using-ajax/43381458#43381458) – Nishanth Matha Apr 13 '17 at 06:00

1 Answers1

5

The copy command used to be protected in all browsers but IE (it would not work in other browsers). Requesting the user use Ctrl+C was a common workaround.

As of Firefox 41 (September 2015), Chrome 42 (April 2015) and Opera 29 (April 2015) this is no longer the case the copy command should be available by default in most major browsers when triggered from certain trusted (user-triggered) events, such as what would be fired in response to a button click.

The compatibility table from MDN, and W3C bug offer further information.

Adam Williams
  • 1,712
  • 3
  • 17
  • 30
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
  • 4
    Yeah but I don't want to press `Ctrl+C` myself, looking for solution to do so programmatically – Dev01 Jan 10 '13 at 08:36
  • 1
    It is impossible without elevated permissions (e.g. as mentioned in this answer with `execCommand`) because allowing arbitrary clipboard injection is considered a security exploit ("clipboard poisoning"). I'm working with the browser vendors to at least get click-to-copy enabled in the modern evergreen browsers so that we can eventually retire ZeroClipboard (or use it as a polyfill for older browsers). – James M. Greene Nov 15 '13 at 19:11
  • @JamesM.Greene, can you link to any bugs you've filed with the browser vendors? – Jeffrey Yasskin Jan 16 '14 at 05:02
  • 2
    @JeffreyYasskin Right now it's just filed as a bug for the communal WebApps Working Group Clipboard API spec (filed by the spec's editor after our mailing list discussions): https://www.w3.org/Bugs/Public/show_bug.cgi?id=23235 Unfortunately, most browser vendors would likely decline a bug report to implement this until the spec bug is resolved and this feature becomes part of the active spec, and the editor has not been able to get around to it yet. :( – James M. Greene Jan 16 '14 at 17:33