【问题标题】:How to copy to clipboard in safari using jquery/javascript?如何使用 jquery/javascript 在 safari 中复制到剪贴板?
【发布时间】:2020-02-26 16:34:58
【问题描述】:

我查看了一堆答案和文章,这些答案和文章显示了如何通过 jquery 在单击按钮时复制文本,但没有一个对我有用。我正在通过 ajax 将一个值附加到 DOM 中,我希望在单击按钮时将其复制。

如果使用 jsfiddle/codepen,所有这些解决方案都可以在 chrome 上运行,并且它们可以在 safari(版本:13.0.5)中运行,但在通过单独的 html 和 js 文件使用时它们在 safari 中不起作用,在我的情况下。

首先我尝试使用位置:绝对和左侧:-99999 进行不可见输入,并使用 jquery 选择其中的文本并使用 execCommand("copy");。这没有用。 我也试过这里提到的答案:Javascript Copy To Clipboard on safari?

我也尝试了下面提到的两个功能,但没有成功。除了这些功能,我还尝试了所有我能找到的 javascript 插件,但这些插件也不起作用。

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

函数2:

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>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    创建一个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!'/>

    【讨论】:

    • 这个,就像我看到的其他一些一样,可以在 sn-p 中工作,也可以在 chrome 上工作。它不适用于最新的 safari 13.0.5
    • 虽然适用于我的版本。我会更深入地研究它。
    • 我在我的 Safari 上尝试了你的代码,它也可以工作。我怀疑它与版本有关。一定有其他原因导致您的问题。也许 JS 在你的 Safari 上被屏蔽了?
    • 不,JS 在我的 safari 上运行得很好。我试图在一个单独的空 html 文件和一个单独的 js 文件上运行你的代码,以防万一有其他东西与进程冲突但没有运气
    【解决方案2】:

    看看这个pen 它适用于Safari。考虑到 document.execCommand('copy') 仅适用于 Safari 版本 10。

    关键部分是使用range来选择内容,像这样:

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

    【讨论】:

    • 我也看到了!但除非这是从 jsfiddle 或 codepen 运行的,否则它甚至不适用于我的 chrome。我在最新的 safari 13.0.5
    • 它不适用于 Chrome,它仅适用于 Safari。我也在 13.0.5 上。
    • 这很奇怪,对我来说,反之亦然,codepen 在 chrome 和 safari 上都可以工作,但是当我复制它以在本地测试它时,它也不能工作。
    猜你喜欢
    • 2017-03-02
    • 1970-01-01
    • 2020-07-23
    • 2021-10-30
    相关资源
    最近更新 更多