在iOS中使用Javascript复制到剪贴板 [英] Copy to clipboard using Javascript in iOS

查看:1280
本文介绍了在iOS中使用Javascript复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此函数将网址复制到剪贴板:

I'm using this function to copy a URL to the clipboard:

function CopyUrl($this){

  var querySelector = $this.next().attr("id");
  var emailLink = document.querySelector("#"+querySelector);

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

  try {  
    // Now that we've selected the anchor text, execute the copy command  
    var successful = document.execCommand('copy', false, null);
    var msg = successful ? 'successful' : 'unsuccessful'; 

    if(true){
        $this.addClass("copied").html("Copied");
    }

  } catch(err) {  
    console.log('Oops, unable to copy');  
  }  

  // Remove the selections - NOTE: Should use   
  // removeRange(range) when it is supported  
  window.getSelection().removeAllRanges();
}

一切都适用于桌面浏览器,但在iOS设备上,返回成功,但数据根本不会复制到剪贴板。这是什么原因,我如何解决这个问题?

Everything works fine on desktop browsers, but not on iOS devices, where my function returns successfully, but the data isn't copied to the clipboard at all. What's causing this and how could I solve this problem?

推荐答案

但是在iOS Safari上,对剪贴板API 有一些限制(实际上是安全措施):

There's no problem with your code. However on iOS Safari there are some restrictions (which actually are security measures) to the Clipboard API:


  • 仅在有效选择项上发生复制事件,

  • 它仅支持通过快捷键读取/写入操作系统剪贴板,而不是通过快捷键读取/写入。 请注意,shorcut键是指一些可点击的(例如复制/粘贴操作菜单或自定义iOS键盘快捷键)或物理键

  • It fires copy events only on a valid selection and cut and paste only in focused editable fields.
  • It only supports OS clipboard reading/writing via shortcut keys, not through document.execCommand(). Note that "shorcut key" means some clickable (e.g. copy/paste action menu or custom iOS keyboard shortcut) or physical key (e.g. connected bluetooth keyboard).
  • It doesn't support the ClipboardEvent constructor.

所以(至少现在)不可能使用Javascript 在iOS设备的剪贴板上以编程方式复制一些文本/值。只有用户可以决定是否复制某些内容。

So (at least as of now) it's not possible to programmatically copy some text/value in the clipboard on an iOS device using Javascript. Only the user can decide whether to copy something.

这篇关于在iOS中使用Javascript复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆