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