3

I looked into a bunch of answers and articles which show how to copy text on button click via jquery but none of them worked for me. I am appending a value through ajax into the DOM and i would like that to be copied on click of a button.

All of these solutions work on chrome and they work in safari (version: 13.0.5) if jsfiddle/codepen is used but they dont work in safari when used via a separate html and js file, in my case anyway.

First i tried to make an invisible input with position: absolute and left: -99999 and selected the text in it using jquery and used execCommand("copy");. This did not work. I also tried the answers mentioned here: Javascript Copy To Clipboard on safari?

I also tried the two functions mentioned below to no luck. In addition to these functions i also tried every javascript plugin i could find and those did not work either.

function 1:

function copy(value, showNotification, notificationText) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val(value).select();
  document.execCommand("copy");
  $temp.remove();
  $(".copyfrom").val(value)
  $(".copyfrom").select();
  document.execCommand("copy");

  //trigger animation---
  if (typeof showNotification === 'undefined') {
    showNotification = true;
  }
  if (typeof notificationText === 'undefined') {
    notificationText = "Copied to clipboard";
  }

  var notificationTag = $("div.copy-notification");
  if (showNotification && notificationTag.length == 0) {
    notificationTag = $("<div/>", { "class": "copy-notification", text: notificationText });
    $("body").append(notificationTag);

    notificationTag.fadeIn("slow", function () {
      setTimeout(function () {
        notificationTag.fadeOut("slow", function () {
          notificationTag.remove();
        });
      }, 1000);
    });
  }
}

function2:

function copyToClipboard(textToCopy) {
  var textArea;

  function isOS() {
    return navigator.userAgent.match(/ipad|iphone/i);
  }

  function createTextArea(text) {
    textArea = document.createElement('textArea');
    textArea.readOnly = true;
    textArea.contentEditable = true;
    textArea.value = text;
    document.body.appendChild(textArea);
  }

  function selectText() {
    var range, selection;

    if (isOS()) {
      range = document.createRange();
      range.selectNodeContents(textArea);
      selection = window.getSelection();
      selection.removeAllRanges();
      selection.addRange(range);
      textArea.setSelectionRange(0, 999999);
    } else {
      textArea.select();
    }
  }

  function copyTo() {
    document.execCommand('copy');
    document.body.removeChild(textArea);
  }

  createTextArea(textToCopy);
  selectText();
  copyTo();

  //trigger animation---
  if (typeof showNotification === 'undefined') {
    showNotification = true;
  }
  if (typeof notificationText === 'undefined') {
    notificationText = "Copied to clipboard";
  }

  var notificationTag = $("div.copy-notification");
  if (showNotification && notificationTag.length == 0) {
    notificationTag = $("<div/>", { "class": "copy-notification", text: notificationText });
    $("body").append(notificationTag);

    notificationTag.fadeIn("slow", function () {
      setTimeout(function () {
        notificationTag.fadeOut("slow", function () {
          notificationTag.remove();
        });
      }, 1000);
    });
  }
}

Here is my ajax and html:

$(".fa-link").on("click", function () {
  var mlink = $(".boxmlink").attr("href").trim()
  var fetchWallID = new XMLHttpRequest()
  fetchWallID.open("POST", db, true);
  fetchWallID.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  fetchWallID.onload = function () {
    if (this.status == 200) {
      var url = $(location).attr("href").split("?")
      var id = (this.responseText).trim()
      var windowurl = url[0].trim()
      var finalurl = (windowurl + '?wallid=' + id).trim().replace("#", '')
      //copy(finalurl, true)
      //copyToClipboard(finalurl)
    }
  }
  fetchWallID.send("mlinkID=" + mlink)
})

html:

<a href="#" class="fa fa-link"></a>
bl4ck120
  • 93
  • 2
  • 9

2 Answers2

2

Creating a textarea element, selecting it and then appending the text to it should solves the issue. Tested on Safari Version 12.0.3. Your version seems to do the same, but with a lot more steps. Please make sure that every part of it works.

function copy(str) {
  const el = document.createElement('textarea');
  el.value = str;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

document.getElementById('button').addEventListener('click', evt => {
  copy(document.getElementById('test').innerHTML);
});
<span id=test>Hello World!</span>
<button id=button>Copy Text</button>
<input placeholder='Paste in Me!'/>
Alain Cruz
  • 4,757
  • 3
  • 25
  • 43
  • this, just like some others i saw, works in the snippet and also works on chrome. It does not work on the latest safari 13.0.5 – bl4ck120 Feb 26 '20 at 20:30
  • Works on my version though. I will dig more into it. – Alain Cruz Feb 26 '20 at 20:35
  • I tried your code on my Safari and it works too. I doubt it has something to do with the version though. There must be something else that is causing your issue. Maybe JS is blocked on your Safari? – Alain Cruz Feb 26 '20 at 21:53
  • nope, JS works totally fine on my safari. i tried to run your code on a separate empty html file and a separate js file just in case there was something else conflicting with the process but no luck – bl4ck120 Feb 27 '20 at 06:47
0

Take a look at this pen it works on Safari. Take into account that document.execCommand('copy') only works as of Safari version 10.

The key part is using a range to select the content, like this:

var range = document.createRange();  
range.selectNode(emailLink);  
window.getSelection().addRange(range);  
Jair Reina
  • 2,606
  • 24
  • 19
  • i saw this too! but unless this is run from jsfiddle or codepen it does not even work on chrome for me. I am on the latest safari 13.0.5 – bl4ck120 Feb 27 '20 at 06:46
  • It doesn't work on Chrome, it only works on Safari. I'm on 13.0.5 as well. – Jair Reina Feb 27 '20 at 16:24
  • thats strange, for me its the other way around, the codepen works both on chrome and safari but when i copy it to test it locally it does not work on either. – bl4ck120 Feb 28 '20 at 07:04