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

送分小仙女□ 提交于 2019-12-06 04:42:12

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14253634/document-execcommand-copy-command-does-not-work-or-other-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!