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

前端 未结 1 485
眼角桃花
眼角桃花 2021-01-06 20:18

This code works fine in Google Chrome, Opera, IE 11. But it doesn\'t work in Mozilla firefox and Safari. I get error in the following string \"var successful = document.exec

相关标签:
1条回答
  • 2021-01-06 20:59

    As of Firefox 41 (September 2015) the copy command should be available by default when triggered from certain trusted (user-triggered) events, such as what would be fired in response to a button click. The compatibility table from MDN offers further information, see also the release notes.

    The code in the question should therefore work. Indeed, I tested something very similar (see code below) and it worked great for me using 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>

    0 讨论(0)
提交回复
热议问题