can't use document.execCommand('copy')

2020-05-07 04:50发布

问题:

can't copy the content of textarea to clipboard using the code below.



    <script>
    function copyText()
    {
    document.getElementById('in').click();
    call();
    }
    function call()
    {
    if(getComputedStyle(document.getElementById('butt')).opacity>0.5)
    {setTimeout(call,100);return;}

    var ta=window.document.createElement("textarea");
    window.document.body.appendChild(ta);
    ta.value="this text should be in clipboard";
    ta.focus();
    ta.selectionStart=0;
    ta.selectionEnd=ta.value.length;
    ta.addEventListener('keypress', function(){window.document.execCommand('copy');});
    var event = new Event('keypress');
    ta.dispatchEvent(event) ;
    }
    </script>
    <button id='butt' onClick='copyText()'>copy text</button>
    <input id='in' type='file' style='display:none;'/>
    <style>
    #butt
    {opacity:0.5;}
    #butt:hover
    {opacity:1;}
    </style>

while if i add an alert() after the setTimeout(call,100) in the if block before return statement.
Text is being copied.
tried it on chrome,opera and firefox every browser responded the same way.
I am using the above structure to copy the base64 encoded text of the file that user opened.

回答1:

Most browsers will only copy text to the clipboard in this way from Javascript that was directly initiated from a real user event (like a click or a key) and not from a setTimeout(). So, if your code takes the setTimeout() path, then it is likely that the copying of the text to the clipboard will not work. You can't just manufacture the keypress event - the whole point of this restriction is to require a real user event, not one manufactured by code.

In case you're interested, here's a tested function to copy text to the clipboard in this answer. It has the same restrictions as any other code - it must be initiated from Javascript that is called by a real user event and it works in modern versions of Chrome, Firefox and IE, but not in Safari.