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