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

时间:2015-05-06 13:50:08

标签: javascript jquery google-chrome 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>

1 个答案:

答案 0 :(得分:5)

从Firefox 41(2015年9月)开始,默认情况下,当从某些受信任(用户触发的)事件触发时,复制命令应该可用,例如响应按钮单击时将触发的事件。来自MDN的compatibility table提供了更多信息,另请参阅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>