0

I need to make a button that will work on every single page and browser that can copy the input from a text area. I am trying to do this with the following function:

 selectElementContents: function(){
      el = document.getElementById("tag_text");

      var range = document.createRange();
      range.selectNode(el);
      window.getSelection().removeAllRanges();
      window.getSelection().addRange(range);

      try {
        var successful = document.execCommand('copy');
      } catch(err) {
        console.log('Oops, unable to copy');
      }

This is currently working fine on all browsers except Firefox and Safari. I read a little about Safari and it seems it does not have support for such a function, or am I mistaken ? However when I try to copy the contents of the input with document.execCommand('copy') it throws the following error: [Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: debugger eval code :: <TOP_LEVEL> :: line 1" data: no] . I looked up this error and it is kind of generic as the code is presented in more than one tipe of errors.

In the end my question is how to make it work on firefox and what is wrong ?

Lucian Tarna
  • 1,453
  • 2
  • 18
  • 40

1 Answers1

2

execCommand('copy') isn't supported everywhere, unfortunately. It also isn't very safe as it puts things into the clipboard without alerting the user.

In any case, you can combine the execCommand('copy') with the solution presented in this answer for non-supported browsers like this:

HTML:

<form id="test_form">
  <p>Copy this:</p>
  <input id="tag_text" type="text" size="40" />
  <input type="button" onClick="select_element_contents()" value="Copy" />
</form>

Javascript:

function select_element_contents (){
    var el = document.getElementById("tag_text");
    var el_text = el.value;

    var range = document.createRange();
    range.selectNode(el);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);

    try {
        var successful = document.execCommand('copy');
    } catch(err) {
        window.prompt("Copy to clipboard: Ctrl+C/Cmd+C, Enter", el_text);
    }
}

This isn't ideal, of course, but as automatic copying to clipboard isn't supported in Mozilla Firefox, the user will have to press the buttons. Might as well make it as transparent as possible.

Community
  • 1
  • 1
Alex Kirko
  • 306
  • 2
  • 7