Как скопировать в буфер обмена в сафари с помощью jquery / javascript? - PullRequest
2 голосов
/ 26 февраля 2020

Я просмотрел кучу ответов и статей, в которых показано, как копировать текст при нажатии кнопки с помощью jquery, но ни одна из них не сработала для меня. Я добавляю значение через ajax в DOM, и я хотел бы, чтобы это было скопировано по нажатию кнопки.

Все эти решения работают на chrome и работают в сафари (версия: 13.0 .5) если используется jsfiddle / codepen, но они не работают в сафари при использовании через отдельный файл html и js, в любом случае, в моем случае.

Сначала я попытался сделать невидимый ввод с позицией : absolute и left: -99999 и выделил текст в нем с помощью jquery и использовал execCommand ("copy") ;. Это не сработало. Я также попробовал ответы, упомянутые здесь: Javascript Копировать в буфер обмена на Safari?

Я также попробовал две функции, упомянутые ниже, но не повезло. В дополнение к этим функциям я также попробовал каждый плагин javascript, который смог найти, и он тоже не работал.

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

Вот мои ajax и 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>

Ответы [ 2 ]

1 голос
/ 26 февраля 2020

Создание элемента textarea, его выделение и добавление к нему текста должно решить проблему. Протестировано на Safari версии 12.0.3. Ваша версия, кажется, делает то же самое, но с гораздо большим количеством шагов. Пожалуйста, убедитесь, что каждая его часть работает.

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!'/>
0 голосов
/ 27 февраля 2020

Взгляните на эту ручку , которая работает в Safari. Примите во внимание, что document.execCommand ('copy') работает только с Safari версии 10.

Ключевая часть использует диапазон для выбора содержимого, например:

var range = document.createRange();  
range.selectNode(emailLink);  
window.getSelection().addRange(range);  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...