不能将 document.execCommand('copy') 与输入类型文件一起使用

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

本文关键字:类型 输入 文件 一起 copy document execCommand 不能      更新时间:2023-09-26

无法将文本区域的内容复制到剪贴板使用以下代码。


    <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>

而如果我在 if 块返回语句中的setTimeout(call,100)后添加一个alert()
正在复制文本。
在Chrome,Opera和Firefox上尝试过,每个浏览器都以相同的方式响应。
我正在使用上述结构来复制用户打开的文件的base64编码文本。

大多数浏览器只会以这种方式从 Javascript 将文本复制到剪贴板,该文本直接从真实用户事件(如单击或键)而不是从setTimeout()启动。 因此,如果您的代码采用setTimeout()路径,则很可能无法将文本复制到剪贴板。 您不能只制造按键事件 - 此限制的重点是需要真实的用户事件,而不是由代码制造的事件。

如果您有兴趣,这里有一个经过测试的函数,可以将文本复制到此答案中的剪贴板。 它与任何其他代码具有相同的限制 - 它必须从由真实用户事件调用的Javascript启动,并且它适用于现代版本的Chrome,Firefox和IE,但不适用于Safari。