execCommand copy async alternative for Firefox

故事扮演 提交于 2019-12-10 10:57:07

问题


document.execCommand('copy') can be used inside the resolve function of a Promise except for Firefox. Every modern browsers like Chrome, Opera, and even Safari allow async copy up to 1 second.

I want to improve the user experience and copy data following a calculation in the clipboard.

Is there a solution to copy the result of a Promise with Firefox in one click?

Here a snippet working with Chrome

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test</title>
</head>
<body>
<button onclick="copy(genPwd)">copy</button>
<script>
    function genPwd() {
        return new Promise(function(resolve) {
            resolve('toto')
        })
    }
    function copy(p) {
        p().then(function(result) {
            console.log('create fake text area');
            var fakeTextArea = document.createElement('textarea');
            fakeTextArea.setAttribute('readonly', '');
            fakeTextArea.value = result;
            document.body.appendChild(fakeTextArea);
            fakeTextArea.select();
            document.execCommand('copy');
        });
    }
</script>
</body>
</html>

来源:https://stackoverflow.com/questions/44550497/execcommand-copy-async-alternative-for-firefox

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