can't use document.execCommand('copy') with input type file

扶醉桌前 提交于 2019-12-04 05:49:15

问题


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.



来源:https://stackoverflow.com/questions/35099600/cant-use-document-execcommandcopy-with-input-type-file

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