简体   繁体   中英

How to copy to clipboard in safari using jquery/javascript?

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>

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!'/>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM