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

Vad*_*suk 2 javascript firefox jquery google-chrome

此代码在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>
Run Code Online (Sandbox Code Playgroud)

Ada*_*ams 5

从Firefox 41(2015年9月)开始,默认情况下,当从某些受信任(用户触发的)事件触发时,复制命令应该可用,例如响应按钮单击时将触发的事件.MDN 的兼容性表提供了更多信息,另请参阅发行说明.

因此,问题中的代码应该有效.实际上,我测试了一些非常相似的东西(见下面的代码),它对我来说非常适合使用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);
})();
Run Code Online (Sandbox Code Playgroud)
textarea {display: block; margin-top: 1em; width: 500px;}
Run Code Online (Sandbox Code Playgroud)
<div id="textToCopy">Elephant</div>
<button id="copyTrigger">Copy above text</button>
<textarea placeholder="Try pasting here to test"></textarea>
Run Code Online (Sandbox Code Playgroud)