简体   繁体   中英

document.execCommand copy command does not work or other solution?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM