如何在 Mozilla Firefox 中一键复制文本?

How can I copy text in one click in Mozilla Firefox?

此代码在 Google Chrome、Opera、IE 11 中运行良好。但在 Mozilla firefox 和 Safari 中不起作用。我在以下字符串中收到错误 "var successful = document.execCommand('copy');"

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Test Copy</title>
    <link href="css/bootstrap-theme.css" rel="stylesheet">
    <link href="css/bootstrap.css" rel="stylesheet">
    <script src="js/bootstrap.js"></script>
    <script src="js/npm.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
        <div id="text">
            Copytextblalalalal
        </div>
        <button id="btnCopy" onclick="copyText()">COPY</button>
    </div>
</div>
<script>
    function copyText() {
        var emailLink = document.querySelector('#text');
        var range = document.createRange();
        range.selectNode(emailLink);
        window.getSelection().addRange(range);

        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy command was ' + msg);
        } catch (err) {
            console.log('Oops, unable to copy');
        }
        window.getSelection().removeAllRanges();
    }
</script>
</body>
</html>

从 Firefox 41(2015 年 9 月)开始,复制命令在从某些受信任的(用户触发的)事件触发时应该默认可用,例如响应按钮单击而触发的内容。 compatibility table from MDN offers further information, see also the release notes.

问题中的代码因此应该有效。事实上,我测试了一些非常相似的东西(见下面的代码)并且它对我使用 Firefox 44 非常有用。

function doCopy() {
    var textToCopy = document.getElementById('textToCopy');
    var range = document.createRange();
    range.selectNodeContents(textToCopy);
    window.getSelection().addRange(range);
    document.execCommand('copy');
}

(function() {
    var el = document.getElementById("copyTrigger");
    el.addEventListener("click", doCopy, false);
})();
textarea {display: block; margin-top: 1em; width: 500px;}
<div id="textToCopy">Elephant</div>
<button id="copyTrigger">Copy above text</button>
<textarea placeholder="Try pasting here to test"></textarea>